当向数组调用此.pop方法时,为什么会得到意外的.length结果

问题描述 投票:1回答:1

我是JS的新手,请多多包涵。当我尝试在定义为.pop的具有24个元素的数组上调用secretMessage方法时,我使用了secretMessage = secretMessage.pop();语法,我认为这是错误的。即使最初有24个元素,在数组上调用.length method也会返回值10。当我使用语法.pop调用secretMessage.pop();方法时,我没有遇到任何问题,返回的.length值为23。为什么语法上的这种差异会影响数组元素的长度?

let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];

secretMessage = secretMessage.pop();
console.log(secretMessage.length); // Returns 10

secretMessage.pop();
console.log(secretMessage.length); // Returns 23 (assuming the previous mutating method is not called beforehand)
javascript arrays syntax
1个回答
0
投票

js pop方法从数组中删除最后一个元素并返回该元素。这将按预期更改数组的长度。

问题是,当您将pop返回的值分配给同一变量时,该变量现在指向数组末尾的对象,而不再指向数组。这个例子:

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
plants = plants.pop();
console.log(plants); //'tomato'

您可以通过检查以下代码来验证这一点:

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
© www.soinside.com 2019 - 2024. All rights reserved.