If I have variables and a for loop with a condition set-up like this:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++)
Does the i refer to the scores array indexed position of 0, or is i just the counter number, which is set to 0?
I'm kinda confused on understanding what's happening.
Any help is appreciated!
Here you can see it in action:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++) {
console.log('i = ' + i + ', scores[i] = ' + scores[i]);
}
console.log('End of for loop: i = ' + i);
One important thing to understand is that i will be incremented until the condition i < arrayLength is not met anymore. So it will reach the value 3 but the for loop will end immediately. Therefore, the code inside the loop is not executed for i = 3.
i is just a counter number which is initially set to 0 and increments up to arrayLength (3 in this case)
i just refers to a number that (in this case) counts up from 0 until arrayLength. You have to explicitly access the values in the array at each i by using scores[i], after which you can modify/use the value in any way you see fit.
i is the counter number.
A for loop works like so:
For each value of array length, use i as a counter variable
each time through the loop increment the variable of i when you are done (i++)
you could expand it like so...
for(i = 0; i < arrayLength; i++)
{
console.log('position ' + i + ' is ' + scores[i]);
}//now that I am done, increment i and go through again until i is no longer less than array length
Right so you have the set the i as a variable by initially going
var i;
Within the for statement you have set the i variable to 0.
for(i = 0; i < arrayLength; i++){
}
Then the for statement is saying if i is less than the array length run the for statement. Each time the for statement runs you are adding 1 to i because of i++;
Every time the for statement will check to see if i is less than the arrayLength if it isnt it will exit out of the for.
So for this instance the for each would run 3 times because the array length is 3.
Make sure you have open and closing brackets on the for statement
So your for statement should look like this.
for(i = 0; i < arrayLength; i++){
}
Related
So I solved the twoSum problem which you can find here: twoSum and I know there are better and more efficient solutions but for this one, I am just trying to understand why I get an empty array unless I reassign variable j inside the while loop. See code below. When I tried solving it by assigning j outside of the loop it doesn't work. See code comments.
My halfway answer/initial thought was that by assigning j's value outside of the loop its doing a direct assignment by value which means its value doesn't change since the interpreter only runs top to bottom and doesn't actually go back to check. So this would mean that if j were to be assigned by reference this problem would not occur?? I don't know if I'm on the right track
var twoSum = function (nums, target) {
let indecesArr = [];
let i = 0;
//j declaration without assignment
let j;
//let j = i + 1; //this will cause return to be empty array
while (i < nums.length) {\
//j's value has to be reassigned here otherwise return is an empty [] array
j = i + 1;
while (j < nums.length) {
if (nums[i] + nums[j] === target) {
indecesArr.push(i, j);
}
j++;
}
i++;
}
return indecesArr;
};
console.log(twoSum([3, 2, 4], 6)); //output [1,2]
You are incrementing the value of j in the inner while loop.
So when i =0 meaning nums[i] = 3 then j increments till the very end as their is no matching pair.
So next time when i = 1 & so on j has already traversed till the end of the array. Code inside the second loop never executes from i=1,hence no matching pair
Tried doing this for a class assignment but for whatever reason it is saying the count is not defined. Any suggestions?
var num = [1,2,3,4,5,6,7,8,9,10]
for(var num = 0; count < 11; num++) {
if(num % 3 ===0);
console.log(num);
}
I think you mean to use the num variable instead of count.
for(var num = 0; num < 11; num++) {
You are defining the 'num' variable. Setting it to 0 and then running the 'for' loop, adding 1 to 'num' for each loop until 'num' is no longer < 11.
try this...
var num = [1,2,3,4,5,6,7,8,9,10];
for (var count = 0; count < num.length; count++) {
if (num[count] % 3 == 0)
alert(num[count]);
}
Typically, Javascript for loops will have this format:
for (i = 0; i < 11; i++) {
//i = 0 > starting index
//i < 11 > ending index
//i++ > index increment
}
The reason why you ran into your error is because count is never defined as a variable, whereas the variable 'i' in my example was defined when I set the value of i=0.
Instead of thinking that you are looping through the integers within the num array, think of it like you're looping through the indexes of num. So within every loop, the i variable will represent which index of the array you're currently focusing on.
Helpful tips:
make sure you utilize num.length to get the ending index of your for loop
Use indexes to reference integers in an array: num[0] == 1,
num[1] == 2, num[2] == 3 ...
Could someone give me an explanation as to why this works
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[0].item);
}
console.log(itemIds); // outputs as expected, the same thing, data.length times
But this does not work (the only change is adding i into the push())
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[i].item);
}
console.log(itemIds); // TypeError: Cannot read property 'item' of undefined
I need to do this as data in this example is coming from an angular $http call, and returning an object. I don't understand why statically putting in 0 works, but trying to make it iterate through each data.item does not.
This is because your variable i will eventually increment above the length of the array.
You need to change your for loop from i <= data.length to i < data.length.
This will ensure that the i variable will always be within the bounds of the array.
Considering that the index is zero-based, but the length will count up from one, the length will always be one more than the highest index.
Here is my dummy explanation.
i can never be equal to data.lenght
If for example:
var data = ['Bob', 'John', 'Mike'];
data[0] = Bob
data[1] = John
data[2] = Mike
data[3] = ?
Therefore data[3] cannot be equal to data.length = 3, it starts looping through 0.
Hope it helps for newbies.
Just to demostrate what goes wrong
basket = ['milk', 'egg', 'chees']
for (var i = 0; i <= basket.length; i++) {
console.log('loop ' + i, basket[i])
}
/*
Logs:
loop 0 milk
loop 1 egg
loop 2 chees
loop 3 undefined
*/
Change
for (var i = 0; i <= data.length; i++)
to
for (var i = 0; i < data.length; i++)
basket = ['milk', 'egg', 'chees']
var x = "";
for (var i = 0; i <= basket.length; i++) {
x = 'loop ' + i, basket[i];
console.log(x);
}
Hope it solves the problem. 'loop ' + i, basket[i]; -- itself creates an empty unidentified element if is not declared with a variable and variable must have an empty content, like this var x = "";
This is a basic for loop question. If I have a simple for loop such as:
function printMe()
{
for(var i = 0; i < 5; i++)
{
document.getElementById("text").innerHTML = i;
}
};
printMe();
When I call the function, it only prints the last number in the loop 5. But, how can I make it print ever iteration of the loop so the final list is 0, 1, 2, 3, 4, 5
You are constantly overwriting the value of innerHTML because you are using innerHTML = i. This means that when the loop has finished running, the value will be the last value of i.
You want to use += to append i to the existing value, and you might want to add a space after that as well so they aren't glued together.
document.getElementById("text").innerHTML += i + " ";
Which is a shorthand notation for
document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + i + " ";
Thus: get the old value, add the new value, store it once again in innerHTML.
The problem is you are assign i into innerHTML each loop (not append +=), so it is an expected behavior to have the only last output
Try the following will be fine
function printMe()
{
for(var i = 0; i < 5; i++)
{
var innerHTML = document.getElementById("text").innerHTML;
document.getElementById("text").innerHTML += (innerHTML.length <= 0 ? "" : ", ") + i;
}
};
printMe();
and also if you would like to print the 5 also, you have to change the for loop to for (var i = 0; i < 6; i++) or for (var i = 0; i <= 5; i++)
try it on https://jsfiddle.net/v1jnLw23/
I was just wondering if I could get some guidance on an issue I am having with nested for loops in javascript.
I currently have the following nested for loop in place
for (var i = 0; i <= score; i++)
{
for (var j = 0; j <= i; j++)
{
var stsc = '<img src="./images/star.png"/>';
}
}
The aim is to get the variable stsc to show the number of stars depending on the count of the score variable.
Currently, it will only show 1 star no matter what the value of score is. I have tried adding stsc outside of the nested loop to no avail. No matter what I do it will show nothing other than 1 star.
Could you point me in the right direction as to how to get it to show the correct number of stars (3 stars if score is 3, 0 stars if score is 0 etc...)
Thanks everyone
var stsc="";
var score=0;
for (var i = 1; i <= score; i++)
{
stsc = stsc +'<img src="./images/star.png"/>';
}
http://jsfiddle.net/m5Btd/1295/
You just need a normal for loop and string concatenation:
var stsc = '';
for (var i = 0; i < score; i++) {
stsc += '<img src="./images/star.png"/>';
}
Think about it like this: You want to create n stars, where n is the value of the score. Hence you have to repeat the process of creating the HTML string n times. That's what a for loop is doing, repeating something until a condition is fulfilled. And instead of overwriting the variable in each iteration, you have to add to it.
You don't need any for loops:
var stsc = score === 0 ? "" : new Array(score + 1).join("<img src=./images/star.png>");