I have an assignment in school where we should grab a text string taken from a promt and then let an alert print the text string 10 times. But we have to use a for-loop. But I can't seem to get it to work even though I read all the pages covering this.
function buttonAction7() {
var someMsg = prompt("Write something");
for(var i = 0; i < 10; i++){
someMsg+someMsg;
}
alert(someMsg);
}
The statement:
someMsg+someMsg;
Doesn't actually do anything, it just returns a logical value. You'll probably want to assign this value to something, such as:
someMsg = someMsg + someMsg; // Notice assignment operator, we're now actually modifying the value of someMsg
If you wanted to build a string with the message 10 times, you'd probably want something more like:
var someMsg = prompt("Write something");
var msg = '';
for(var i = 0; i < 10; i++)
{
msg += someMsg + '\n'; // Add a line break after each iteration
}
window.alert(msg);
If i understand what you're asking, you want the alert to display the string 10 times back to back in the same alert window? (like "Write somethingWrite somethingWrite something..."):
If that is correct then your issue is your computation inside your for loop. You are simply add the two strings together, but doing nothing with the result. You need to save the result back to the someMsg variable on each loop iteration, like this:
var someMsg = promt("Write something");
var output = "";
for(var i=0; i<10; i++) {
output = output + someMsg;
}
alert(output);
You see how the result of output+someMsg is being saved back to the variable output with each iteration. You can also write that short hand like this:
output += someMsg;
Try this.
var someMsg=prompt("Write Something");
var i;
for(i=0;i<10;i++){
alert(someMsg);
}
Related
My teacher gave us a lesson where we had to find out how many times a x number was drawn in the lottery. He gave us a .txt document containing all datas from the previous years. He told us to build a function to discover these values. I ended up with this:
//Transfer the txt logs to variable 'conteudo'
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i++){
conteudo[i] = conteudo[i].split(";");
for(j = 2; j < 8; j++){
if(conteudo[i][j] == a){
vezessort += 1;
}
}
}
}
//In this exercise we need to capture the input from user, and use it as a parameter on the function
a = parseInt(prompt('Digite um número: '));
r = vezSort(a);
console.log(`O número foi sorteado ${vezessort} vezes.`);
It works perfectly, the final values matches with the desired output he gave. The problem is, in the next question he tell us to loop the function for each number between 1 to 60. But every attempt I try to loop I get problems with this line: conteudo[i] = conteudo[i].split(";");. What I am doing wrong? (Btw, in this exercise the input from the user is not needed.)
The problem is that you're modifying the conteudo array when you call vezSort(). It's initially an array of strings, but you're changing it to a 2-dimensional array when you do conteudo[i] = conteudo[i].split(";");
You should either convert it to a 2-dimensional array just once, outside the vezSort() function, or use a local variable rather than modifying the original array.
Doint it once is more efficient, so that's how I show it:
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
conteudo = conteudo.map(line => line.split(';'));
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i++){
for(j = 2; j < 8; j++){
if(conteudo[i][j] == a){
vezessort += 1;
}
}
}
}
.split() turns a string into an array of substrings, not an array into a string. For that, use .join().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
I am looking for a way to print out a given variable f.ex. the i of a for-loop for each iteration, without it resulting in the entire console being filled with new lines of new values. Is there a console. method for just printing one line, and updating that as we go?
I realise that you could do this by implementing a text-field in your program which you change the with each iteration, but if there is a way of doing this in the console it would be a bit easier (and perhaps quicker? although I am really not sure about that). Thanks in advance.
If there is still confusion about what im asking, what i want is my console to print out:
"i = " i once, and then update the i in that one line, instead of:
i=1
i=2
i=3
1=4
.
.
.
which gets really messy as you go. For the exact example of the i in a for loop, you could get this value from just console.log()'ing the same thing for each iteration, and a number will pop up beside it (in firefox anyway), but i would like to be able to do this with some more useful information.
Option 1: use console.groupCollapsed() and console.groupEnd():
console.groupCollapsed();
for (let i = 0; i < 100; i+= 1) { console.log(`i = ${i}`) }
console.groupEnd();
Option 2: set the values in an array or a string and log the var when the iterations finish:
let valuesToLog = [];
for (let i = 0; i < 100; i+= 1) { valuesToLog.push(`i = ${i}`) }
// see it as an array
console.log(valuesToLog);
// see it as a string, with each value separated by ', '
console.log(valuesToLog.join(', '));
how about JQuery console.clear()?
$(function(){
loop_counter();
});
function loop_counter() {
for (let i = 1; i <= 100; i++){
console.clear();
console.log ("i=", i)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Context: I am creating a table of content to inform user of the page(s) that they have completed/visited.
The if...else statement below is working (by itself) but i want to generate the check for the other 30 chapters using the "i" counter from the FOR loop.
The script will first load the localstorage that contains the value 1 or 0 representing visited / unvisited and transfer that data onto variable chap1check. based on the result, the table of content should then show the user which page have or have not been visited.
im not sure of what i need to do but in theory, i will need to replace all the "chap1..." with the value of "i".
<script type="text/javascript">
var i;
for (i = 1; i <=31; i++){
var chap1Check = localStorage.getItem("chap1Status");
if(chap1Check == "1"){
document.getElementById('chap1Completion').innerHTML = "Completed";
}else{
document.getElementById('chap1Completion').innerHTML = "Incomplete";
}
}
</script>
Just concatenate the part of the string before the number with the number (i), followed by the part of the string after the number.
for (var i = 1; i <= 31; i ++){
var chapCheck = localStorage.getItem("chap" + i + "Status");
document.getElementById('chap' + i + 'Completion').textContent = chapCheck == "1" ? "Completed" : "Incomplete";
}
The following code will work. However, it would be much cleaner for you to just store an Array in local storage, and access it by indexing the array. Also, take a look into using the map functor over a for loop.
Note also that you should inline the declaration of i in the for loop as shown below. Otherwise, you may get conflicts with any future use of i in a for loop.
for (var i = 1; i <=31; i++){
var chapterChecker = localStorage.getItem("chap"+i+"Status");
if(chap1Check == "1"){
document.getElementById('chap'+i+'Completion').innerHTML = "Completed";
}else{
document.getElementById('chap'+i+'Completion').innerHTML = "Incomplete";
}
}
A solution using es6 template string could be this
for (var i = 1; i <=31; i++){
let content = '';
if(localStorage.getItem(`chap${i}Status`) == "1"){
content = "Completed";
}else{
content = "Incomplete";
}
document.getElementById(`chap${i}Completion`).innerHTML = content;
}
My goal's create a filter search function, in particular actually I'm using .indexOf method that allow me to check if two string are equal. The problem's that if I've the compare string with space break like this: Hair Cut.
Example:
String to search: Hair
String contained in the object: Hair Cut
var cerca = $('#filter_service').val();
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
if (cerca.toLowerCase().contains(GlobalVariables.availableServices[i].name.toLowerCase()) != -1) {
console.log(GlobalVariables.availableServices[i].name)
}
}
How you can see I valorize the variable cerca that contains the string Hair in the example. I compare this with an object variable, how I said, the problem is if I insert the string Hair I get no response in console, also if I insert the string with break space like the compare string Hair Cut I get the console response.
How I can print a result also when the variable cerca is equal to the first character of the compair string? In particular Hai?
I don't know if I was clear, hope yes.
.contains() is for checking DOM element children. You said above that you are using .indexOf to check, but it doesn't look like you use it in your code?
var cerca = $('#filter_service').val();
var searchIn;
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
searchIn = GlobalVariables.availableServices[i].name.toLowerCase().split(' ');
for (j = 0; j < searchIn.length; j++) {
if (cerca.toLowerCase().split(' ').indexOf(searchIn[j].toLowerCase()) >= 0) {
console.log(GlobalVariables.availableServices[i].name);
}
}
}
$('#filter_service').on('input', function() {
var inputStr = $('#filter_service').val();
var similar = [];
for (i = 0; i < GlobalVariables.availableServices.length; i++) {
if (GlobalVariables.availableServices[i].name.toLowerCase().indexOf(inputStr.toLowerCase) >= 0) {
similar[similar.length] = GlobalVariables.availableServices[i].name;
}
}
// At this point, you can do whatever you want with the similar service
// names (all of the possible result names are included in the array, similar[].)
});
I can't test that code right now, but in theory, it should work.
Here is a JSFiddle demo:
http://jsfiddle.net/MrGarretto/vrp5pghr/
EDIT: Updated and fixed my errors
EDIT 2: Added the 'possible results' solution
EDIT 3: Added a JSFiddle
I'm trying to read in a csv string to a 2D array and for some reason it stops when it gets to the second iteration of the first loop.
Here's the Fiddle and the code:
$(document).ready(function(){
var lay = [[]];
document.getElementById("result").innerHTML = value;
bits = value.split(',');
console.log(bits.length);
elm = bits.length/4;
count=0;
console.log(bits[6]); //here it reads but won't assign to the array
for (i=0; i<=elm; i++)
{lay[i]=[];
console.log('i:'+i);
for (j=0; j<=4; j++)
{ console.log('j:' + j);
console.log('count:' + count);;
lay[i][j] == bits[count];
count = count + 1;
console.log('bit value:' + bits[count]);
}
}
console.log(lay[0][0]);
});
The value for the next element reads and displays, but when I try to assign the data to the array it errors out.
Fixed Code
added the redeclaration of the array in the first loop
That made the error go away.
Fiddle
Thanks!
Something wrong with u'r lay array I think.
Is this element set? lay[i][j]
I think I solved it
http://jsfiddle.net/hgm8r/3/
I've made two changes:
Declared the `lay' value outside the loop
var lay = Array();
And updated it at the start of the first loop
lay[i] = Array();
And now it runs without errors.