我是 JS 新手,请耐心等待。当我尝试对定义为 secretMessage
(有 24 个元素)的数组调用 .pop
方法时,我使用了语法 secretMessage = SecretMessage.pop();
我相信这是错误的。对数组调用 .length 方法
返回值 10,即使最初有 24 个元素。当我使用语法 secretMessage.pop();
调用 .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)
最佳答案
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"]
关于javascript - 当对数组调用此 .pop 方法时,为什么我会得到意外的 .length 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997769/