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

arr.insert(index, item)

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


当前回答

使用Array.prototype.splice()是实现它的一种简单方法

常量数=[“一”、“二”、“四”、“五”]数字拼接(2,0,“三”);console.log(数字)

阅读有关Array.prototype.splice的更多信息

其他回答

解决方案和性能

今天(2020.04.24),我为大型和小型阵列选择的解决方案进行测试。我在Chrome 81.0、Safari 13.1和Firefox 75.0上的macOS v10.13.6(High Sierra)上测试了它们。

结论

适用于所有浏览器

令人惊讶的是,对于小型阵列,基于切片和归约(D,E,F)的非就地解决方案通常比就地解决方案快10x-100倍对于大型阵列,基于拼接(AI、BI和CI)的就地解决方案是最快的(有时约为100倍,但取决于阵列大小)对于小型阵列,BI解决方案是最慢的对于大型阵列,E解决方案是最慢的

细节

测试分为两组:就地解决方案(AI、BI和CI)和非就地解决方案,分别针对两种情况进行:

测试包含10个元素的数组-可以在此处运行测试具有1000000个元素的数组-可以在此处运行

测试代码显示在以下代码段中:

小提琴演奏家

函数AI(arr,i,el){arr.splice(i,0,el);返回arr;}功能BI(arr,i,el){阵列.原型.拼接.应用(arr,[i,0,el]);返回arr;}函数CI(arr,i,el){数组.原型.拼接.调用(arr,i,0,el);返回arr;}函数D(arr,i,el){返回arr.slice(0,i).contat(el,arr.slices(i));}函数E(arr,i,el){return[…arr.slice(0,i),el,…arr.slime(i)]}函数F(arr,i,el){返回arr.reduce((s,a,j)=>(j-i?s.push(a):s.push(el,a),s),[]);}// -------------//测试// -------------设arr=[“a”、“b”、“c”、“d”、“e”、“f”];设log=(n,f)=>{设a=f([…arr],3,“新”);console.log(`${n}:[${a}]`);};日志('AI',AI);日志('BI',BI);日志('CI',CI);日志('D',D);对数('E',E);日志('F',F);此代码段仅显示测试代码(不执行测试)

Google Chrome上一个小数组的示例结果如下:

为了实现正确的函数编程和链接目的,Array.protocol.insert()的发明是必不可少的。实际上,如果拼接返回的是变异数组,而不是一个完全没有意义的空数组,那么它可能是完美的。因此,这就是:

Array.prototype.insert=函数(i,…rest){此.拼接(i,0,…其余)返回这个}变量a=[3,4,8,9];document.write(“<pre>”+JSON.stringify(a.insert(2,5,6,7))+“</pre>”);

好吧,好吧,上面的Array.prototype.splice()一个变异了原始数组,有些人可能会抱怨“你不应该修改不属于你的东西”,这可能也是正确的。因此,为了公益,我想提供另一个Array.prototype.insert(),它不会对原始数组进行变异。就这样;

Array.prototype.insert=函数(i,…rest){返回this.slice(0,i).contat(rest,this.slict(i));}变量a=[3,4,8,9],b=插入件(2,5,6,7);console.log(JSON.stringify(a));console.log(JSON.stringify(b));

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

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]

多用途ARRAY和ARRAY OF OBJECT可重用方法

设arr=[0,1,2];让obj=〔{name:“abc”},{name::“xyz”};const addArrayItemAtIndex=(数组,索引,newItem)=>{return[…array.sslice(0,索引),newItem,…array.sSlice(索引)];}//对于阵列console.log(addArrayItemAtIndex(arr,2159));//对于对象阵列console.log(addArrayItemAtIndex(obj,0,{name:“AMOS”}));

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

这将检查项目是否存在:

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: