如何在特定索引处将项目插入数组中?

4211
我正在寻找一种JavaScript数组插入方法,类似于:
arr.insert(index, item)

最好使用jQuery,但目前任何JavaScript实现都可以。

151
请注意,jQuery是一个DOM和事件操作的库,而不是一种独立的编程语言。它与数组操作无关。 - Domino
36
https://api.jquery.com/jQuery.inArray/与DOM或事件无关。jQuery已经发展成为一个混合工具包,用于浏览器JS开发,导致人们期望它拥有一切方法。 - Tim
8
@Tim,但它仍然不是一种独立的语言(在SO上仍然有一些类似“如何在jQuery中求两个数字之和”的问题)。 - Victor
10
不,而且永远不会再是。jQuery曾经很有用且相关,但它已经过时了。 - Tim
我很烦恼这个问题的标题和页面标题不同(jQuery vs. JS)。在搜索结果中显示不同。 - Andrew
32个回答

6
我必须同意Redu的答案,因为splice()接口确实有点令人困惑。cdbajorin给出的回答是,“当第二个参数为0时,它只返回一个空数组。如果大于0,则返回从数组中删除的项目”,虽然准确,但证明了这一点。
该函数的目的是拼接或像Jakob Keller早先说的那样“连接,也可以改变”。
您有一个已经建立好的数组,现在正在更改其中的元素,这将涉及添加或删除元素....”鉴于此,如果有任何被删除的元素,则其返回值可能会很尴尬。我完全同意,如果该方法返回自然的新数组,其中包含已剪切的元素,则该方法更适合链式操作。然后,您可以使用返回的数组做任何您喜欢的事情,例如["19", "17"].splice(1,0,"18").join("...")等等。
它返回被删除的内容有点荒谬,我的看法是如此。如果该方法的意图是“剪掉一组元素”,并且这是它唯一的意图,那么也许可以。不过,如果我已经不知道要剪掉什么,我可能没有理由去剪掉那些元素,不是吗?
如果它的行为类似于concat()、map()、reduce()、slice()等,从现有数组中创建一个新的数组而不是修改现有数组,那就更好了。它们都是可链接的,这是一个重要问题。链式操作数组处理非常常见。
似乎语言需要朝一个方向发展并尽可能地坚持下去。JavaScript是一种功能性语言,比较不具声明性,它似乎与规范有所偏离。

5
以下是我在一个应用程序中使用的可行函数。
这个函数检查一个项目是否存在:
let ifExist = (item, strings = [ '' ], position = 0) => {
     // Output into an array with an empty string. Important just in case their isn't any item.
    let output = [ '' ];
    // Check to see if the item that will be positioned exist.
    if (item) {
        // Output should be equal to an array of strings.
        output = strings;
       // Use splice() in order to break the array.
       // Use positional parameters to state where to put the item
       // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
        output.splice(position, 0, item);
    }
    // Empty string is so we do not concatenate with comma or anything else.
    return output.join("");
};

然后我在下面调用它。

ifExist("friends", [ ' ( ', ' )' ], 1)}  // Output: ( friends )
ifExist("friends", [ ' - '], 1)}  // Output:  - friends
ifExist("friends", [ ':'], 0)}  // Output:   friends:

请问您能否解释一下您的解决方案? - De Bonheur

5

我喜欢一点安全性,所以我使用了这个:

Array.prototype.Insert = function (item, before) {
  if (!item) return;
  if (before == null || before < 0 || before > this.length - 1) {
    this.push(item);
    return;
  }
  this.splice(before, 0, item);
}


var t = ["a", "b"]

t.Insert("v", 1)

console.log(t)


6
你说你喜欢安全,那就建议修改基本原型!这是逻辑吗? - blazkovicz
3
没错,这是我对安全的定义..哈哈。 - hossein sedighian

2
如果你想保持原始数组不变,但返回一个在特定索引处插入元素的新数组,你可以使用新的 `toSpliced()` 方法:
这样可以避免对数组进行原地修改。

//                0    1    2
const letters = ["A", "B", "D"];
const insertIndex = 2; // position in the array to insert 
const correctLetters = letters.toSpliced(insertIndex, 0, "C"); // 0 means don't delete any items, just insert. "C" is the item you want to insert.
console.log(correctLetters); // ["A", "B", "C", "D"] (new array contains new char)
console.log(letters); // ["A", "B", "D"] (unmodified)

如果你需要将多个项目插入到数组中,就像它的兄弟方法.splice()一样,你可以使用.toSpliced()并传入多个参数:
.toSpliced(insertIndex, 0, "C", "D", "E");

以上的例子将在指定的插入索引处将 "C"、"D" 和 "E" 插入数组中,而不会修改原始数组,而是返回一个新的数组。

1

以下是一段支持同时插入多个值的简单函数:

function add_items_to_array_at_position(array, index, new_items)
{
    return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

使用示例:

let old_array = [1,2,5];

let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);

console.log(new_array);

//Output: [1,2,3,4,5]

这与许多现有答案类似,但结合了函数/展开运算符/多个项/示例/输出的简洁组合,尚未发布。 - Pikamander2

1
var array= [10,20,30,40]

var i;

var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/

var value=5 
//value to insert

//Initialize from last array element

for(i=array.length-1;i>=pos-1;i--){

array[i+1]=array[i]

}

array[pos-1]=value

console.log(array)

2
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

1

我是这样做的:

const insert = (what, where, index) => 
  ([...where.slice(0, index), what , ...where.slice(index, where.length)]);

const insert = (what, where, index) =>
  ([...where.slice(0, index), what , ...where.slice(index, where.length)]);
  
const list = [1, 2, 3, 4, 5, 6];
const newList = insert('a', list, 2);

console.log(newList.indexOf('a') === 2);


1
这是现代(使用Typescript函数式编程)的方法:
export const insertItemInList = <T>(
  arr: T[],
  index: number,
  newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]

1

多用途的数组对象数组的可重复使用方法

let arr = [0,1,2];
let obj = [{ name: "abc"},{ name: "xyz"},{ name: "ijk"} ];

const addArrayItemAtIndex = ( array, index, newItem ) => {
    return [...array.slice(0, index), newItem, ...array.slice(index)];
}

// For Array
console.log( addArrayItemAtIndex(arr, 2,  159 ) );

// For Array of Objects
console.log( addArrayItemAtIndex(obj, 0, { name: "AMOOS"} ) );


1
//Suppose we have an array  
let myArray = [2, 4, 6, 8, 10];  

// Index where we want to insert the item  
let indexToInsert = 3;  

// Item we want to insert  
let itemToInsert = 174;  

// Now we Using splice() method to insert the item at the specified index  
myArray.splice(indexToInsert, 0, itemToInsert);  

// output with new value    
console.log(myArray);  

你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接