Hello, is it possible to sustain a variable the same as it was after using the pop() method?
var i = ["one", "two", "three", "four"]
document.write(i)
var n = i.pop()
document.write(i)
For example, can the “n” variable be set to the last item of the “i” array without removing that item from the array?
miku86
August 3, 2020, 8:29am
2
Hey there,
good question!
You can use slice
to create a copy:
var i = ["one", "two", "three", "four"];
console.log("before", i);
var n = i.slice().pop();
console.log("after", i);
// ["one", "two", "three", "four"]
MDN: slice
1 Like
To get the value of the last element in an array, you could access the index array.length - 1
.
const nums = [1, 2, 3, 4, 5];
const lastNum = nums[nums.length - 1];
console.log(nums); // [1, 2, 3, 4, 5];
console.log(lastNum); // 5
ILM
August 3, 2020, 10:10am
4
why not just var n = i.slice(-1)
?
miku86
August 3, 2020, 12:28pm
5
Yes, you are right,
I was focused on pop
ping it.
This would return the last value in an array, pop returns only the value.
ILM
August 10, 2020, 6:17am
7
then add a [0]
at the end of it