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

arr.insert(index, item)

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


当前回答

不可变插入

如果您需要插入到阵列中的适当位置,使用拼接方法无疑是最佳答案。

但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时对原始数组进行变异,那么可以使用以下函数。

函数插入(数组,索引){const items=Array.prototype.slice.call(arguments,2);return[].contat(array.sslice(0,索引),items,array.sslict(索引));}常量列表=['one','two','three'];const list1=插入(列表,0,“零”);//插入单个项目const list2=insert(列表,3,'four','five','sive');//插入多个console.log('原始列表:',列表);console.log('插入的列表1:',列表1);console.log('插入的列表2:',列表2);

注意:这是ES6之前的一种实现方式,因此它适用于较旧和较新的浏览器。

如果您使用的是ES6,那么您也可以尝试其他参数;看看这个答案。

其他回答

有两种方法:

const array=['My','name','Hamza'];array.拼接(2,0,'is');console.log(“方法1:”,array.join(“”));

Or

Array.prototype.insert=函数(索引,项){此.拼接(索引,0,项);};const array=['My','name','Hamza'];array.insert(2,'is');console.log(“方法2:”,array.join(“”));

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

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

首先是源对象,一个从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);

不可变插入

如果您需要插入到阵列中的适当位置,使用拼接方法无疑是最佳答案。

但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时对原始数组进行变异,那么可以使用以下函数。

函数插入(数组,索引){const items=Array.prototype.slice.call(arguments,2);return[].contat(array.sslice(0,索引),items,array.sslict(索引));}常量列表=['one','two','three'];const list1=插入(列表,0,“零”);//插入单个项目const list2=insert(列表,3,'four','five','sive');//插入多个console.log('原始列表:',列表);console.log('插入的列表1:',列表1);console.log('插入的列表2:',列表2);

注意:这是ES6之前的一种实现方式,因此它适用于较旧和较新的浏览器。

如果您使用的是ES6,那么您也可以尝试其他参数;看看这个答案。

我试过了,效果很好!

var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);

索引是要插入或删除元素的位置。

0,即第二个参数,定义要从索引中删除的元素的数量。项包含要在数组中创建的新条目。它可以是一个或多个。

initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");

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

这将检查项目是否存在:

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: