【问题标题】:Insert an array in the middle of an existing array. Keep the existing reference intact在现有数组的中间插入一个数组。保持现有参考不变
【发布时间】:2014-08-19 17:10:00
【问题描述】:

假设我有两个数组:

var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];

假设我还有另一个对 numbers 数组的引用:

var anotherRef = numbers;

我想以修改现有数组的方式将一个插入另一个,以便在操作后anotherRef === numbers

如果我不需要维护原始数组,我会这样做:

function insert(target, source, position) {
  return target.slice(0, position).concat(source, target.slice(position));
}

问题是,用这种方法插入后,两个引用指向不同的数组:

numbers = insert(numbers, letters, 3);
numbers !== anotherRef; // sadly, true.

如果我要添加到数组的末尾,我可以这样做,这有点巧妙:

function insertAtEnd(target, source) {
  Array.prototype.push.apply(target, source);
}

有没有很好的方法在 JS 数组中插入多个值?

【问题讨论】:

  • 我被第一位搞糊涂了:“手术后,anotherRef === numbers”。这不是 before 任何操作的情况吗?由于它们指向同一个数组,因此对任何一个执行的任何操作都将由任一引用反映
  • @AndrewWhitaker,是的,以前是这样,我也需要以后也是这样。问题是 concat 返回一个新数组,切片也是如此。 splice 没有,但它不处理数组中的多个参数。

标签: javascript arrays


【解决方案1】:

您似乎正在寻找splice 方法:

function insert(target, source, position) {
    Array.prototype.splice.apply(target, [position, 0].concat(source));
    return target;
}
var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];

insert(numbers, letters, 3);
console.log(numbers);
>> [1, 3, 5, "a", "b", "c", 7, 9, 11]

【讨论】:

  • [position, 0].concat(source):我一直在寻找的聪明解决方案。漂亮!
【解决方案2】:

工作示例:http://jsfiddle.net/0mwun0ou/1/

function insert(target, source, position) {
  Array.prototype.splice.apply(target, [position,0].concat(source));
}

var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];

var anotherRef = numbers

insert(numbers, letters, 1)

console.log(anotherRef)

我从未接触过anotherRef,但在该示例中,输出为:

[1, "a", "b", "c", 3, 5, 7, 9, 11] 

关于如何使用数组作为拼接检查的第三个参数的说明:Is there a way to use Array.splice in javascript with the third parameter as an array?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2015-09-26
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多