Javascript 对数组调用此.pop方法时,为什么会得到意外的.length结果
我是JS的新手,所以请容忍我。当我试图对定义为Javascript 对数组调用此.pop方法时,为什么会得到意外的.length结果,javascript,arrays,syntax,Javascript,Arrays,Syntax,我是JS的新手,所以请容忍我。当我试图对定义为secretMessage的数组调用.pop方法时,该数组有24个元素,我使用了语法secretMessage=secretMessage.pop()
secretMessage
的数组调用.pop
方法时,该数组有24个元素,我使用了语法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返回的值赋给同一个变量时,该变量现在指向数组末尾的对象,而不再指向数组。
这是一个例子:
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"]
js方法从数组中删除最后一个元素并返回该元素。这将按预期更改数组的长度
问题是,当您将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"]
对数组使用.pop()
将从数组中删除最后一个元素并返回弹出的值。因此,您将secretMessage
设置为等于从数组中删除/弹出的值。我猜您在secretMessage
中的最后一个元素是一个长度为10的字符串,在数组中使用.pop()
将从数组中删除最后一个元素并返回弹出的值。因此,您将secretMessage
设置为等于从数组中删除/弹出的值。我猜您在secretMessage
中的最后一个元素是一个长度为10的字符串