【问题标题】:Javascript splice gives different outputJavascript拼接给出不同的输出
【发布时间】:2022-01-14 05:22:26
【问题描述】:

这是我在使用 splice 时遇到的一个奇怪行为。

const numbers = [1, 2, 3];
numbers.splice(0, 0, 4, 5);
console.log(numbers); // This gives output [4, 5, 1, 2, 3] 

console.log([1, 2, 3].splice(0, 0, 4, 5)) // Outputs []

这是为什么呢?

【问题讨论】:

  • Splice 对原始数组进行变异,并返回删除的项目数组。由于您没有删除任何内容,因此返回的数组为空。

标签: javascript arrays splice


【解决方案1】:

这是预期的行为。 splice 返回已删除项目的数组,在您的情况下,没有删除任何元素。 splice 实际上修改了原始数组。阅读文档here

【讨论】:

    【解决方案2】:

    Array.splice 函数本身返回从第一个参数开始到第二个参数结束的元素范围。第二个参数之后的所有内容都会自动添加到原始数组的末尾,但它不会作为操作的结果返回。

    const numbers = [1, 2, 3];
    console.log(numbers.splice(0, 0, 4, 5)) // <- prints nothing because your sequence is from 0 to 0.
    

    【讨论】:

      【解决方案3】:

      splice 方法不返回输出,而是修改原始数组。

      【讨论】:

      • 它确实返回值,如果您提供的范围在原始范围内包含元素
      【解决方案4】:

      JavaScript Array splice() 替换原始数组元素

      array.splice(index, how_many_element, item1, ....., itemX);
      const numbers = [1, 2, 3];
      
      
      console.log(numbers.splice(0, 0, 4, 5)) // <- here index = 0, how_many_element = 0, deferent = 0, that is why prints nothing because your sequence is from 0 to 0.
      

      index :添加/删除项目的位置; how_many_element:要删除的项目数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-03
        相关资源
        最近更新 更多