【问题标题】:When calling this .pop method to an array, why am I getting an unexpected .length result将此 .pop 方法调用到数组时,为什么会得到意外的 .length 结果
【发布时间】:2020-05-16 18:17:10
【问题描述】:

我是 JS 新手,请多多包涵。当我尝试在定义为secretMessage(有24 个元素)的数组上调用.pop 方法时,我使用了secretMessage = secretMessage.pop(); 语法,我认为这是错误的。调用数组上的.length method 返回值 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)

【问题讨论】:

  • 在数组上使用.pop() 将删除数组中的最后一个元素并返回弹出的值。因此,您将 secretMessage 设置为等于从数组中删除/弹出的值。我猜secretMessage 中的最后一个元素是一个长度为 10 的字符串

标签: javascript arrays syntax


【解决方案1】:

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"]

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多