Reputation: 3
I would like to know:
I know you can assign a value to an array in a for loop by using indexing.
My question is:
I have a for loop that looks like this:
for (i=array_len-2;i>0;i-=2)
{
var new_arry=array[i]
}
... that would just return the value for i
. It does not store it in the new array.
but, if i do that same thing:
for (i=array_len-2;i>0;i-=2)
{
var new_arry=array.push(i)
}
it adds the new element in the array in the format of [element one , element two].
Upvotes: 0
Views: 62
Reputation: 657
You'll want to use indexes for anything that should be in a specific index if it doesn't matter you can probably use push()
which will return the new length and it is said on this other post that is faster than indexes.
Upvotes: 0
Reputation: 11184
The following example shows, how you should use the index i
and the push
method.
var myArray = ["hello", "world", "welcome", "javascript", "user"];
var newArray = new Array();
for(var i=myArray.length-2; i>0; i-=2) {
newArray.push(myArray[i]);
}
console.log(newArray);
A push()
simply add anything you pass as argument to an array.
Index i
are used to identify the "index location" on an array.
Upvotes: 1
Reputation: 43880
Either way works, just create an empty array outside the loop. Use the incrementing variable as you progress through each iteration (loop). Avoid using keyword new
when making arrays, it's 99% better to use literal ex. var array = [];
Keep in mind that the loop in your examples go backward (-=2
) and it's unusual in that that it stops early (i=array_len-2;i>0;
), normally a loop is set at full length (i=array_len
which is derived from var array_len = array.length
most likely). So this unorthodox loop will only add 2 extra elements if the array is only 4 to 5 in length (I might be off...).
// Fill array by push()
var arr1 = [];
for (let i=0; i < 5; i++) {
arr1.push(i);
}
console.log(arr1);
// Fill array by assignment
var arr2 = [];
for (let i=0; i< 5; i++) {
arr2[i] = i;
}
console.log(arr2);
Upvotes: 1