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

arr.insert(index, item)

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


当前回答

为了实现正确的函数编程和链接目的,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));

其他回答

尽管这个问题已经得到了回答,但我还是添加了这个注释作为替代方法。

我想将已知数量的项目放入一个数组中,放入特定位置,因为它们来自一个“关联数组”(即一个对象),根据定义,该数组不能保证按排序顺序排列。我希望得到的数组是一个对象数组,但是对象在数组中的顺序是特定的,因为数组保证了它们的顺序。所以我这样做了。

首先是源对象,一个从PostgreSQL检索的JSONB字符串。我想让它按每个子对象中的“order”属性排序。

var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';

var jsonb_obj = JSON.parse(jsonb_str);

由于对象中的节点数是已知的,因此我首先创建一个具有指定长度的数组:

var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);

然后迭代对象,将新创建的临时对象放置到数组中所需的位置,而不进行任何“排序”。

for (var key of Object.keys(jsonb_obj)) {
  var tobj = {};
  tobj[key] = jsonb_obj[key].abbr;

  var position = jsonb_obj[key].order - 1;
  sorted_array[position] = tobj;
}

console.dir(sorted_array);

解决方案和性能

今天(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上一个小数组的示例结果如下:

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

这将检查项目是否存在:

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:

另一种可能的解决方案,使用Array.reduce。

const arr=[“苹果”、“橙色”、“覆盆子”];常量arr2=[1,2,4];常量插入=(arr,项,索引)=>arr.reduce(函数,a,i){i==索引?s.push(项目,a):s.push(a);返回s;}, []);console.log(插入(arr,“香蕉”,1));控制台日志(插入(arr2,3,2))

在特定索引处附加单个元素

// Append at a specific position (here at index 1)
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element


// Append at a specific position (here at index 3)
arrName[3] = 'newName1';

在特定索引处附加多个元素

// Append from index number 1
arrName.splice(1, 0, 'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where append start,
// 0: number of element to remove,
//newElemenet1,2,3: new elements