【问题标题】:Why is arguments.length not changing even after appending new value to the array?为什么即使将新值附加到数组后,arguments.length 也不会改变?
【发布时间】:2021-07-06 14:35:12
【问题描述】:

function test(num0, num1) {
  console.log(arguments.length); // output: 1
  arguments[1] = 20;
  console.log(arguments.length); // output: 1
}

test(8);

但是当对普通数组执行相同的操作时,数组的长度会发生变化-

var arr = [2];
console.log(arr.length); // output: 1
arr[1] = 5;
console.log(arr.length); // output: 2

那么为什么arguments[]数组的长度在为新索引赋值后没有改变?

【问题讨论】:

  • arguments 是一个数组like 对象。比[8] 多思考{length: 1, 0: 8}
  • arguments 不是数组,而是类似数组。任何适用于数组的东西都不适用于arguments
  • @jonrsharpe 所以如果我将此对象转换为数组,那么该数组的索引 0 应该存储长度的值?
  • 否;如果将其转换为数组,则第 0 个索引处的值将是第一个参数 8。
  • @NinaScholz 但 arguments.length 返回一个适用于数组但不适用于对象的值。

标签: javascript arrays function arguments


【解决方案1】:

Argument 不是一个数组而是一个类似数组的对象,它没有像我们在数组中那样使用 [] 运算符来分配值(仅用于读取)。一种解决方案是将参数转换为数组,然后继续处理新对象。

function test(num0, num1) {
  var arg = Array.from(arguments);
  console.log(arg.length); // output: 1
  arg[1] = 20;
  console.log(arg.length); // output: 2
}

test(8);

【讨论】:

  • 这个参数对象是否将其长度存储为一个数据元素,如 arguments = {length: 1, 0:8}
  • arguments 对象确实“有 [] 运算符”;如问题所示,您可以按索引分配arguments[1] = 20。您还可以通过索引获取值,例如console.log(arguments[0])。当您像数组一样分配超出最后一个索引时,它只是不会更新长度属性,因为它不是数组。
  • 嘿@PracticalMinds,它没有相同的长度字段,在上面的例子中“长度”是数组属性。
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 2017-06-03
  • 2015-03-25
  • 2023-03-20
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多