var obj = {‘id’:1, ‘name’:2}
delete obj.id
delete obj[id]
console.log(obj)// {‘name’:2}
删除数组中指定元素
var objArray = [‘1’,’2’,’3’,’4’]
objArray.remove(‘1’)
console.log(objArray)// [‘2’,’3’,’4’]
/*定义js数组删除元素/
Array.prototype.remove = function(val) {
var index = this.indexOf(val)
if (index >-1) {
this.splice(index, 1)
}
}
使用方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var str = '[{"name":"aa","age":"23"},{"name":"bb","age":"24"},{"name":"cc","age":"25"}]'
var array=JSON.parse(str)
array.push({"name":"dd","age":"25"})
//修改
var obj=array.firstOrDefault(
function(x){
return x.name=='bb'
}
)
obj.age=25
//删除
array.delete(
function(x){
return x.name=='cc'
}
)
//转为json字符串
str=JSON.stringify(array)
js代码文件js.js
//----------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Array.prototype.firstOrDefault = function (predicate) {
var first = null
if (typeof predicate == "undefined") {
if (this.length >0)
first = this[0]
} else if (typeof predicate == "function") {
for (var i = 0i <this.lengthi++) {
if (predicate(this[i])) {
first = this[i]
break
}
}
} else {
throw new Error("predicate 类型必须为function")
}
return first
}
Array.prototype.delete = function (predicate) {
if (typeof predicate == "function") {
var obj = this.firstOrDefault(predicate)
if (obj) {
delete obj
}
} else {
throw new Error("predicate 类型必须为function")
}
}