我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
使用Array.prototype.splice()是实现它的一种简单方法
常量数=[“一”、“二”、“四”、“五”]数字拼接(2,0,“三”);console.log(数字)
阅读有关Array.prototype.splice的更多信息
其他回答
您需要在本机阵列对象上使用拼接函数。
arr.splice(索引,0,项);将在指定的索引处向arr中插入项目(首先删除0个项目,也就是说,这只是一个插入)。
在本例中,我们将创建一个数组,并将一个元素添加到索引2中:
var arr=[];arr[0]=“Jani”;arr[1]=“Hege”;arr[2]=“过时”;arr[3]=“Kai Jim”;arr[4]=“博格”;console.log(arr.jjoin());//Jani、Hege、Stale、Kai Jim、Borgearr.splice(2,0,“Lene”);console.log(arr.jjoin());//Jani、Hege、Lene、Stale、Kai Jim、Borge
我喜欢一点安全,我用这个:
Array.prototype.Insert=函数(项,之前){if(!item)返回;if(before==null|| before<0|| before>this.length-1){this.push(项目);回来}此.拼接(之前,0,项);}var t=[“a”,“b”]t.插入(“v”,1)控制台日志(t)
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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:
除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用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]
有两种方法:
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(“”));