我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
我正在寻找一个JavaScript数组插入方法,样式如下:
arr.insert(index, item)
最好是在jQuery中,但此时任何JavaScript实现都可以。
当前回答
任何对这个问题仍有疑问的人,都尝试过前面答案中的所有选项,但都没有得到。我分享我的解决方案,这是为了考虑到您不想显式地声明对象与数组的财产。
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;
}
这是对引用数组进行迭代并将其与要检查的对象进行比较的组合,将两者转换为字符串,然后在匹配时进行迭代。然后你就可以数了。这是可以改进的,但这是我解决的问题。
其他回答
下面是一个支持同时插入多个值的简单函数:
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]
var array= [10,20,30,40]
var i;
var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/
var value=5
//value to insert
//Initialize from last array element
for(i=array.length-1;i>=pos-1;i--){
array[i+1]=array[i]
}
array[pos-1]=value
console.log(array)
使用Array.prototype.splice()是实现它的一种简单方法
常量数=[“一”、“二”、“四”、“五”]数字拼接(2,0,“三”);console.log(数字)
阅读有关Array.prototype.splice的更多信息
这是我在一个应用程序中使用的一个工作函数。
这将检查项目是否存在:
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#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)];