如何刪除 Array 中的 Object ?
栏目: JavaScript · 发布时间: 7年前
内容简介:ECMAScript 提供了ECMAScript 5因為
ECMAScript 提供了 splice() 刪除 Array 中的 Element,但必須先提供要刪除的 Index ;但若要刪除的是 Object,由於 Object 的比較是 Reference,所以 Index 取得方式比較不一樣。
Version
ECMAScript 5
splice()
錯誤寫法
const data = [
{id: 1, name: 'Sam'},
{id: 2, name: 'Kevin'},
{id: 3, name: 'Mike'},
];
const target = {id: 2, name:'Kevin'};
const index = data.indexOf(target);
if (index !== -1) data.splice(index, 1);
console.log(data);
因為 splice() 需要有 index ,直覺會使用 indexOf() 取得 index ,但 target 為 object,所以比較的是 reference。
因為 data array 內的 object 與 target 的 reference 不相同,因此 index 為 -1 ,也就是永遠無法正確刪除資料。
正確寫法
let data = [
{ id: 1, name: 'Sam' },
{ id: 2, name: 'Kevin' },
{ id: 3, name: 'Mike' },
];
const target = { id: 2, name:'Kevin' };
const fn = x => !(x.id === target.id && x.name === target.name);
data = data.filter(fn);
console.log(data);
indexOf() 有另外一個 findIndex() 版本,傳入的是 function。
由於我們要比較的是 object 內的 property value,而非 object reference,因此要使用的是 findIndex() ,傳入自己要判斷的 property value。
filter()
let data = [
{ id: 1, name: 'Sam' },
{ id: 2, name: 'Kevin' },
{ id: 3, name: 'Mike' },
];
const target = { id: 2, name:'Kevin' };
const fn = x => !(x.id === target.id && x.name === target.name);
data = data.filter(fn);
console.log(data);
splice() 的缺點是直接去修改 array 本身,而且必須先找到 index ,可改用 filter() 找到所有 不符合條件 的資料,再指定給 data 。
Conclusion
-
indexOf()找不到 object,因為新建立 object 有新的 reference,因此indexOf()找不到 -
splice()是直接修改 array;而filter()是回傳新 array
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。