我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
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)];
其他回答
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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:
在这种情况下,我建议使用纯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…)
我试过了,效果很好!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
索引是要插入或删除元素的位置。
0,即第二个参数,定义要从索引中删除的元素的数量。项包含要在数组中创建的新条目。它可以是一个或多个。
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
多用途ARRAY和ARRAY OF OBJECT可重用方法
设arr=[0,1,2];让obj=〔{name:“abc”},{name::“xyz”};const addArrayItemAtIndex=(数组,索引,newItem)=>{return[…array.sslice(0,索引),newItem,…array.sSlice(索引)];}//对于阵列console.log(addArrayItemAtIndex(arr,2159));//对于对象阵列console.log(addArrayItemAtIndex(obj,0,{name:“AMOS”}));
您可以使用array.spling执行此操作:
/**
* @param arr: Array
* @param item: item to insert
* @param index: index at which to insert
* @returns array with the inserted element
*/
export function _arrayInsertAt<T>(arr: T[], item: T, index: number) {
return arr.splice(index, 0, item);;
}
阵列切片的文档