js删除某个数组的特定对象以及js判断某个数组是否有某个对象,没有则添加
1、js删除某个数组的特定对象
var arrs = [{key:'write',name:'write',value:'写'},{key:'read',name:'write',value:'读'}];
removeArray(arrs,'write');
function removeArray(arrs,name) {
var length = arrs.length
for (var i = 0; i < length; i++) {
if (arrs[i].key == name) {
if (i == 0) {
arrs.shift() //删除并返回数组的第一个元素
return arrs
} else if (i == length - 1) {
arrs.pop() //删除并返回数组的最后一个元素
return arrs
} else {
arrs.splice(i, 1) //删除下标为i的元素
return arrs
}
}
}
}
2、js判断某个数组是否有某个对象,没有则添加
var arrs = [{key:'write',name:'write',value:'写'},{key:'read',name:'write',value:'读'}];
function addArray(arrs) {
var option = {key:'write',name:'write',value:'写'}
if (JSON.stringify(arrs).indexOf(JSON.stringify(option)) == -1) {
arrs.push(option)
}
}