Home > Software design >  Problem removing the last element from an array
Problem removing the last element from an array

Time:10-04

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);

CodePudding user response:

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);

CodePudding user response:

You can try something like this

var array = [1, 2, 3, 4, 5, 6];
array.pop();
console.log(array);

CodePudding user response:

You can use:

array.splice(-1)

More here

CodePudding user response:

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);

CodePudding user response:

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.

  • Related