我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
有两种方法:
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(“”));
其他回答
不可变插入
如果您需要插入到阵列中的适当位置,使用拼接方法无疑是最佳答案。
但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时对原始数组进行变异,那么可以使用以下函数。
函数插入(数组,索引){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,那么您也可以尝试其他参数;看看这个答案。
除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用ES6排列运算符。
常量项=[1,2,3,4,5]常量插入=(arr,索引,newItem)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10)console.log(结果)// [1, 10, 2, 3, 4, 5]
这可以用于添加多个项目,方法是稍微调整函数,为新项目使用rest运算符,并在返回的结果中传播:
常量项=[1,2,3,4,5]常量插入=(arr,索引,…newItems)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目…新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10,20)console.log(结果)// [1, 10, 20, 2, 3, 4, 5]
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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:
按以下方式计算减少方法的利润:
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要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。
我试过了,效果很好!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
索引是要插入或删除元素的位置。
0,即第二个参数,定义要从索引中删除的元素的数量。项包含要在数组中创建的新条目。它可以是一个或多个。
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");