我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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))
在这种情况下,我建议使用纯JavaScript。JavaScript中也没有任何insert方法,但我们有一个内置Array方法,它为您完成任务。这叫做拼接。。。
让我们看看什么是拼接()。。。
splice()方法通过删除现有元素和/或添加新元素。
好的,假设我们有下面这个数组:
const arr = [1, 2, 3, 4, 5];
我们可以这样删除3个:
arr.splice(arr.indexOf(3), 1);
它将返回3,但如果我们现在检查arr,我们有:
[1, 2, 4, 5]
到目前为止,还不错,但我们如何使用拼接将新元素添加到数组中?
让我们把三个放回。。。
arr.splice(2, 0, 3);
让我们看看我们做了什么。。。
我们再次使用拼接,但这次对于第二个参数,我们传递了0,这意味着我们不想删除任何项,但同时,我们添加了第三个参数,即将在第二个索引中添加的3。。。
您应该知道,我们可以同时删除和添加。例如,现在我们可以做到:
arr.splice(2, 2, 3);
这将删除索引2中的两个项目。然后在索引2处添加3,结果将是:
[1, 2, 3, 5];
这显示了拼接中的每个项目是如何工作的:
array.拼接(开始,删除计数,项目1,项目2,项目3…)
您可以使用splice()进行此操作
splice()方法在添加元素时通常会收到三个参数:
要添加项的数组的索引。要删除的项目数,在本例中为0。要添加的元素。
let array=['item 1','item 2','item 3']让insertAtIndex=0let itemsToRemove=0array.spling(insertAtIndex,itemsToRemove,'在索引0上插入此字符串')console.log(数组)
您需要在本机阵列对象上使用拼接函数。
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#splice()是最好的方法,除非你真的想避免改变数组。给定2个数组arr1和arr2,下面是如何将arr2的内容插入到arr1的第一个元素之后:
常量arr1=[‘a’,‘d’,‘e’];常量arr2=['b','c'];arr1.拼接(1,0,…arr2);//arr1现在包含[a','b','c','d','e']控制台日志(arr1)
如果您担心数组的变异(例如,如果使用Immutable.js),可以改用slice(),不要与带有“p”的splice()混淆。
const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];