我正在寻找一个JavaScript数组插入方法,样式如下:

arr.insert(index, item)

最好是在jQuery中,但此时任何JavaScript实现都可以。


当前回答

我喜欢一点安全,我用这个:

Array.prototype.Insert=函数(项,之前){if(!item)返回;if(before==null|| before<0|| before>this.length-1){this.push(项目);回来}此.拼接(之前,0,项);}var t=[“a”,“b”]t.插入(“v”,1)控制台日志(t)

其他回答

您需要在本机阵列对象上使用拼接函数。

arr.splice(索引,0,项);将在指定的索引处向arr中插入项目(首先删除0个项目,也就是说,这只是一个插入)。

在本例中,我们将创建一个数组,并将一个元素添加到索引2中:

var arr=[];arr[0]=“Jani”;arr[1]=“Hege”;arr[2]=“过时”;arr[3]=“Kai Jim”;arr[4]=“博格”;console.log(arr.jjoin());//Jani、Hege、Stale、Kai Jim、Borgearr.splice(2,0,“Lene”);console.log(arr.jjoin());//Jani、Hege、Lene、Stale、Kai Jim、Borge

我不得不同意Redu的回答,因为splice()的界面确实有点混乱。cdbajorin给出的响应是“当第二个参数为0时,它只返回一个空数组。如果它大于0,则返回从数组中删除的项“虽然准确,但证明了这一点。

该功能的目的是拼接,或者如Jakob Keller先前所说,“连接或连接,也改变。

您有一个已建立的阵列,现在正在更改,这将涉及添加或删除元素。。。。“考虑到这一点,被删除的元素(如果有的话)的返回值充其量是尴尬的。我100%同意,如果该方法返回了一个看起来很自然的新数组,添加了拼接元素,则该方法可能更适合于链接。然后,您可以对返回的数组执行类似[”19“,”17“].splice(1,0,”18“).join(”…“)之类的操作。

它返回删除的内容这一事实简直是无稽之谈。如果该方法的目的是“删除一组元素”,而这是它唯一的目的,也许。似乎如果我不知道我已经剪了什么,我可能没有什么理由剪掉这些元素,不是吗?

如果它表现得像concat()、map()、reduce()、slice()等,从现有数组生成新数组,而不是改变现有数组,那会更好。这些都是可链接的,这是一个重要的问题。链数组操作非常常见。

似乎语言需要朝一个或另一个方向发展,并尽可能地坚持下去。JavaScript具有功能性,声明性较低,这似乎是一种与规范的奇怪偏差。

这是我在一个应用程序中使用的一个工作函数。

这将检查项目是否存在:

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:

自定义数组插入方法

1.具有多个参数和链接支持

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    this.splice.apply(this, [index, 0].concat(
        Array.prototype.slice.call(arguments, 1)));
    return this;
};

它可以插入多个元素(与原生拼接一样)并支持链接:

["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]

2.支持数组类型参数合并和链接

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    index = Math.min(index, this.length);
    arguments.length > 1
        && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
        && this.insert.apply(this, arguments);
    return this;
};

它可以将参数中的数组与给定数组合并,还支持链接:

["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"

演示:http://jsfiddle.net/UPphH/

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

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]