我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
不可变插入
如果您需要插入到阵列中的适当位置,使用拼接方法无疑是最佳答案。
但是,如果您正在寻找一个不可变函数,该函数返回一个新的更新数组,而不是在插入时对原始数组进行变异,那么可以使用以下函数。
函数插入(数组,索引){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,那么您也可以尝试其他参数;看看这个答案。
其他回答
下面是一个支持同时插入多个值的简单函数:
function add_items_to_array_at_position(array, index, new_items)
{
return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}
用法示例:
let old_array = [1,2,5];
let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);
console.log(new_array);
//Output: [1,2,3,4,5]
使用Array.prototype.splice()是实现它的一种简单方法
常量数=[“一”、“二”、“四”、“五”]数字拼接(2,0,“三”);console.log(数字)
阅读有关Array.prototype.splice的更多信息
为了实现正确的函数编程和链接目的,Array.protocol.insert()的发明是必不可少的。实际上,如果拼接返回的是变异数组,而不是一个完全没有意义的空数组,那么它可能是完美的。因此,这就是:
Array.prototype.insert=函数(i,…rest){此.拼接(i,0,…其余)返回这个}变量a=[3,4,8,9];document.write(“<pre>”+JSON.stringify(a.insert(2,5,6,7))+“</pre>”);
好吧,好吧,上面的Array.prototype.splice()一个变异了原始数组,有些人可能会抱怨“你不应该修改不属于你的东西”,这可能也是正确的。因此,为了公益,我想提供另一个Array.prototype.insert(),它不会对原始数组进行变异。就这样;
Array.prototype.insert=函数(i,…rest){返回this.slice(0,i).contat(rest,this.slict(i));}变量a=[3,4,8,9],b=插入件(2,5,6,7);console.log(JSON.stringify(a));console.log(JSON.stringify(b));
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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:
有两种方法:
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(“”));