我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用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]
其他回答
我试过了,效果很好!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
索引是要插入或删除元素的位置。
0,即第二个参数,定义要从索引中删除的元素的数量。项包含要在数组中创建的新条目。它可以是一个或多个。
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
在这种情况下,我建议使用纯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…)
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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:
您可以使用splice()进行此操作
splice()方法在添加元素时通常会收到三个参数:
要添加项的数组的索引。要删除的项目数,在本例中为0。要添加的元素。
let array=['item 1','item 2','item 3']让insertAtIndex=0let itemsToRemove=0array.spling(insertAtIndex,itemsToRemove,'在索引0上插入此字符串')console.log(数组)
任何对这个问题仍有疑问的人,都尝试过前面答案中的所有选项,但都没有得到。我分享我的解决方案,这是为了考虑到您不想显式地声明对象与数组的财产。
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj))
count++;
});
return count > 0;
}
这是对引用数组进行迭代并将其与要检查的对象进行比较的组合,将两者转换为字符串,然后在匹配时进行迭代。然后你就可以数了。这是可以改进的,但这是我解决的问题。