【问题标题】:Why does splice not fill the holes on a javascript array?为什么 splice 不能填充 javascript 数组上的孔?
【发布时间】:2013-07-03 08:06:09
【问题描述】:

假设你运行这段代码:

var a = [];
a[4] = true;

那么你的数组看起来像[undefined, undefined, undefined, undefined, true]

但是如果你运行这段代码:

var a = [];
a.splice(4, 0, true);

你会得到[true] 而不是[undefined, undefined, undefined, undefined, true]

当使用拼接时,如果索引超过了数组的当前长度,它会在最后一个元素处停止。

为什么这是拼接的预期行为?

【问题讨论】:

  • 您使用的javascript引擎/浏览器是什么?
  • 也许您应该直接联系从事 ECMScript 标准工作的人? Stack Overflow 不一定是获得有关特定语言设计决策的权威答案的最佳场所。
  • @bfuoco: [4: true] 看起来不像一个数组。
  • @bfuoco 试试var a = []; a.splice(4, 0, true); console.log(a);
  • "那么你的数组看起来像 [undefined, undefined, undefined, undefined, true]" - 不完全是。 a[4]=true 在索引4 处添加一个元素并将.length 设置为5,但它不会在先前的索引位置添加undefined 元素。如果您执行console.log(a),它可能看起来是这样,而a[0]===undefined 将是true,但这是因为访问不存在的属性会返回undefined,而不是因为属性存在并且已设置为该值undefined。您可以看到元素 03 实际上并不存在,因为 (0 in a) 是 false

标签: javascript splice


【解决方案1】:

根据 ECMA 文档,'start' 参数不能大于数组的长度或设置为数组的长度。

5 - 让 relativeStart 为 ToInteger(start)。

6 - 如果 relativeStart 为负数,则让 actualStart 为 max((len + relativeStart),0);否则让 actualStart 为 min(relativeStart, len)。

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.12

至于为什么:我不确定,也许他们认为如果该方法将项目添加到数组中会违反直觉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多