I am learning Javascript and have run into an issue with the push method. When I use it within a loop it is making my array 33 items instead of just adding 3 to the list. Initial list is 1-10 items long, user defined. I initiated all the variables in the beginning of the script, and the variable items is only manipulated when the user initially tells me how long the array will be. From there it is basic exercises in array methods, and this is the one that is giving me problems. Following is the push part of the code. I appreciate any feedback and will put more code up if anyone feels it is necessary.
for (i = 0 ; i < 3 ; i++){
newfood = prompt("Please enter food " + (i + 1) + ".");
foods.push(newfood);
}
document.write("<ol>");
i = 0; //resetting variable i to 0
for (i = 0 ; i < items + 3 ; i++){
document.write("<li>" + foods[i] + "</li><br>");
}
document.write("</ol>");
Looks like you're running into string concatenation that's then treating the string as a numeric type. Convert what I assume is a string to an int:
for (i = 0 ; i < parseInt(items) + 3 ; i++) {
document.write("<li>" + foods[i] + "</li><br>");
}
Related
I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}
In strictly native JS, is there a way to display a string and variable in one alert window (or other window)? For now, let's ignore fancy things like jQuery, Vue, Node, etc.
var testNumber = prompt("Enter a number. Let us see how many even numbers
are therein.");
var countEvens = 0;
for (var i = 0; i <= testNumber; i++) {
if (i % 2 === 0){
countEvens++;
}
}
alert("There are " countEvens " even numbers in" testNumber);
Obviously you can. just ad + operator to concatenate. alert("There are " +countEvens +"even numbers in"+testNumber);
var testNumber = prompt("Enter a number. Let us see how many even numbers are therein.");
var countEvens = 0;
for (var i = 0; i <= testNumber; i++) {
if (i % 2 === 0){
countEvens++;
}
}
alert("There are " +countEvens +" even numbers in" +testNumber);
In strictly native JS, there is no alert or any other mechanism for showing output. JS depends on the host environment to provide that sort of API.
A web browser's alert method will pay attention only to the first argument, which it converts to a string if it isn't one already.
If you want to construct your string from multiple variables and literals you can use concatenation:
alert("There are " + countEvens + " even numbers in " + testNumber);
or template strings:
alert(`There are ${countEvens} even numbers in ${testNumber}`);
I just have a question about some while loop logic.
So, when you write a loop that displays a string of numbers to a document and say that while the loop is <= (less than or equal to) say, 5, and you tell the loop to add 1 each time this is true, wouldn't that mean that: while the loop is equal to 5 that it would add one to 5 too? It doesn't, but I messed up on some code when I was practicing and noticed that when it is equal to five it does not add one, but I thought it would...
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text); // Should print `1 2 3 4 5 `.
the reason your text doesn't display a 6 isn't because i isn't incremented. It's because the text gets added onto before it's incremented.
In other words when executing on that 5th loop, the text would add on 5, and then it would increment i, and then it would check the loop again, which would no longer be valid and therefore 6 is never printed.
In memory, it adds one. It doesn't add it to the text though.
Since you're incrementing the value after assigning it and then the loop condition fails, it doesn't get to the part where you concatenate the string.
It does. Just output i and you'll see it's 6. text never gets the 6 because of when you increment i.
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text,i); // Should print `1 2 3 4 5 `.
b/c you +1 after you add i to text, all you need to do is switch the two line order.
EDIT
if you want it start with one just change your i to 0 to start with.
i = 1
console.log('2nd Loop:');
text = '';
i = 0;
while (i <= 5) {
i += 1
text += i + ' ';
}
console.log(text);
I am working on Chapter 2 Exercise 3 in Eloquent Javascript, Chess Board. I am having an issue understanding one part and hoping someone would be able to provide a little enlightenment.
My Code:
var size = 7;
var board = "";
for(var i = 0; i <= size; i++){
for(var j = 0; j <= size; j++){
if((i + j) % 2 === 0){
board += " ";
} else {
board += "#";
}
}
board += "\n";
}
console.log(board);
The issue that I am having is with the condition of the "if" statement.
if((i + j) % 2 === 0)
I am not understanding why I need to add i and j together. Isn't the first "for" loop that contains the i variable constructing the row and how many rows? Where as, the second "for" loop that contains the j variable is creating the content within each row?
The addition of i and j is to create the checkerboard pattern. If the sum is even, a white square (" ") is printed; otherwise it is black ("#").
Also, your conditional statement contains a triple equals sign instead of the desired ==.
It is creating a checker board pattern so the rows are off by one on each iteration. If the row was not used, it would create stripes.
Currently with i + j % 2
# # # #
# # # # #
# # # #
# # # # #
If it were just j % 2
# # # #
# # # #
# # # #
# # # #
If it were just i % 2
.
########
########
########
I think I'am a little late to answer but will do so anyway.
Its because your want to create a pattern that looks like something like this.
"# # # #"
" # # # "
therefor you are going to add the variable "i" that is used to count from your outer loop and the variable "j" from your inner loop that is used to count, to decide with the help of an if/else statement to output either a "#" or " "(space). Also not that your first outer loop will stay at 0 until the vairable "j" in your inner loop is equal to "size". Meaning that one the first run (i+j) is = to 0+1, 0+2, 0+3, 0+4, 0+5, 0+6, 0+7. Once the inner loop is done the outer loop adds a "\n" and the procces is repeated but this time your outer loop vairable that is used to count changes from 0 to 1 and your inner loop variable that is used to count resets to 0 and your expression (i+j) is now equal to 1+0, 1+2, 1+3 ect
var size = 7;
var board = "";
for(var i = 0; i <= size; i++){ /*This will remain 0 the first run until the inner loop is completed then it will add the "\n" at the end*/
for(var j = 0; j <= size; j++){/* the variable j here will keep adding 1 to itslef until it j is equal to size*/
if((i + j) % 2 === 0){/* here it will add both i+j then divide it by 2 in order to see if is an even number or not.
remember it will look something like the this first run 0+1, 0+2, 0+3 ect.*/
board += " ";// here if the number is even it will output a (space)
} else {
board += "#";// here if the number is not even it adds "#"
} // finally this inner loop gets repeated until your vairable "j" is equal to "size"
}
board += "\n";/* then the outer loop adds a new line and your vairable "i"
becomes 1 and this whole loop gets reapeated until "i" is equal to "size"*/
}
console.log(board);
hope this helped excuse my grammar, my english is not that good greetings from Mexico City
Hi I've been having so trouble with this project I need to change colors or matching numbers in 2 arrays, but have the remaining numbers stay there natural color.
for(d = 0; d < lotteryNums.length; d++) {
for(x = 0; x < quickDrawNums.length; x++) {
if(lotteryNums[d] == quickDrawNums[x]) {
quickDrawNums[x] = "<span class='winner'>" + quickDrawNums[x] + "</span>";
winCounter++;
} else {
quickDrawNums[x] = "<span class='number'>" + quickDrawNums[x] + "</span>";
}
}
}
When I have this display it gives me 5 empty boxes and 1 box with the number in it. It also stops my match if from working I was just wondering if anybody could help me sort this out. Thanks for the help in Advance :)
You need to remove the "else" because you are re-writing all the quickDrawNums every time the next lotteryNums is selected. This would result in only on class ='winner' on the last lotteryNums item. Not sure why the empty boxes appear. Verify the original "else" has correct spelling and case for objects, etc.