delete 删除数组方法:
function removeJSONRows() {
var tab = {
"dataRows": [
{"id": 1,"name": "使用部门"},
{"id": 2,"name": "车辆走行路线"},
{"id": 3,"name": "使用类别"}
]
}
var rs = tab['dataRows'];
for (var i in rs) {
if (rs[i]['id'] === 2) {
// delete 方法仅将数组中元素删除,数组空间位置还保留着,因此,删除后的数组长度依然为3。
delete rs[i];
}
}
console.log(rs);
console.log(JSON.stringify(rs), rs.length);
}
----------------------------------------------------------------------------------------------------------------------
splice 删除数组方法:
function removeJSONRows() {
var tab = {
"dataRows": [
{"id": 1,"name": "使用部门"},
{"id": 2,"name": "车辆走行路线"},
{"id": 3,"name": "使用类别"}
]
}
var rs = tab['dataRows'];
for (var i in rs) {
if (rs[i]['id'] === 2) {
// splice 方法将数组中元素彻底删除,删除后的数组长度为2。
rs.splice(i,1);
}
}
console.log(rs);
console.log(JSON.stringify(rs), rs.length);
}
----------------------------------------------------------------------------------------------------------------------
filter 方法删除数组元素
function removeJSONRows() {
var tab = {
"dataRows": [
{"id": 1,"name": "使用部门"},
{"id": 2,"name": "车辆走行路线"},
{"id": 3,"name": "使用类别"}
]
}
// filter 删除等价于 splice 方法,彻底将元素从数组中清除掉。
var rs = tab['dataRows'].filter((rows) => rows['id'] != 2);
console.log(rs);
console.log(JSON.stringify(rs), rs.length);
}