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

arr.insert(index, item)

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


当前回答

按以下方式计算减少方法的利润:

function insert(arr, val, index) {
    return index >= arr.length
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

因此,通过这种方式,我们可以返回一个新数组(这将是一种很酷的函数方式,比使用push或splice要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。

其他回答

按以下方式计算减少方法的利润:

function insert(arr, val, index) {
    return index >= arr.length
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

因此,通过这种方式,我们可以返回一个新数组(这将是一种很酷的函数方式,比使用push或splice要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。

自定义数组插入方法

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/

以下是现代(字体功能)方式:

export const insertItemInList = <T>(
  arr: T[],
  index: number,
  newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]

我这样做:

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

常量插入=(what,where,index)=>([…where.slice(0,index),what,…where.slice(index,where.length)]);常量列表=[1,2,3,4,5,6];const newList=插入('a',列表,2);console.log(newList.indexOf('a')==2);

任何对这个问题仍有疑问的人,都尝试过前面答案中的所有选项,但都没有得到。我分享我的解决方案,这是为了考虑到您不想显式地声明对象与数组的财产。

function isIdentical(left, right){
    return JSON.stringify(left) === JSON.stringify(right);
}

function contains(array, obj){
    let count = 0;
    array.map((cur) => {
        if(this.isIdentical(cur, obj)) 
            count++;
    });
    return count > 0;
}

这是对引用数组进行迭代并将其与要检查的对象进行比较的组合,将两者转换为字符串,然后在匹配时进行迭代。然后你就可以数了。这是可以改进的,但这是我解决的问题。