Reputation: 11
N.B. I am a complete JavaScript beginner.
My assignment is to create an empty array and assign it to a variable. Then, using a for loop, place the numbers 0 to 5 into the array. Then I need to remove the last number in the array and console.log the result.
Any thoughts on why .pop()
isn't working? It works when I use it on an array that I construct without a for
loop. Thanks.
var numberList = new Array();
for (let numberList = 0; numberList < 6 ; numberList++)
console.log(numberList);
numberList.pop();
console.log(numberList);
Upvotes: 0
Views: 555
Reputation: 159
There are multiple issues in the code.
var numberList = new Array();
for (let index= 0; index< 6 ; index++){
numberList.push(index);
}
console.log(numberList);
numberList.pop();
console.log(numberList);
Upvotes: 1
Reputation: 64
the problem is that you are not inserting items on your array, you're just reassigning the value of numberList
You can try something like that instead:
var numberList = new Array();
for (let i = 0; i < 6 ; i++) {
numberList.push(i);
}
console.log(numberList);
numberList.pop();
console.log(numberList);
So this way you're pushing the value of i
into your array, then removing the last one in te end.
Upvotes: 0
Reputation: 89159
You did not add any elements to the array. Use Array#push
to do so.
let numberList = new Array();
for (let i = 0; i < 6 ; i++) numberList.push(i);
console.log(...numberList);
numberList.pop();
console.log(...numberList);
Upvotes: 1
Reputation: 7591
You're not pushing anything into the array. Right now, all you do is writing to the console. You need to use Array.push(). Also, you overwrite the numberList array with an integer in your for loop.
var numberList = new Array();
for (let i = 0; i < 6 ; i++) {
numberList.push(i);
}
console.log(numberList);
numberList.pop();
console.log(numberList);
Upvotes: 1
Reputation: 9
You can try something like this
var array = [1, 2, 3, 4, 5, 6];
array.pop();
console.log(array);
Upvotes: 0