问题描述
我正在搜索对象数据响应,并检测其是否包含“ wdt ”。但是我正在努力销毁或 删除 ,将其与我的data
一起处理。
不相信有像 delete 这样的有效关键字可以在JavaScript中做到这一点?
我目前正在尝试splice
,但是它似乎无效。仍在我的console.log(data);
let data = await getData();
filterChkpt();
function filterChkpt(){
for (let i = 0; i < data.length; i++) {
if (data[i].url.indexOf('wdt') > -1) {
console.log(data[i]);
data[i].splice(index,1); // here would like to remove matches
} else {
// console.log('else: ',data[i].url);
}
}
}
console.log(data);
if (!this.data) {
this.data = {};
}
this.data.storage = new Memory({ data });
return this;
解决方法
这不是解决方案,而是对代码为何无法按预期工作的解释
a = [a,b,c,d,e,f]
i=0 => a
i=1 => b
i=2 => c ( now you decide to splice the array >> a = [a,f]
i=3 => e! ( you missed the "d" cos it was shifted to the left
每次拼接数组时都应该i--
除非出于某些原因需要对原始对象进行突变,否则array.filter就是要这样做的。 (这吓到我在迭代对象时修改对象。)
const data = Array.from({length: 10},() => ({ url: Math.random() > 0.5 ? 'foo' : 'bar' }));
console.log(data);
console.log(data.filter(x => x.url === 'foo'));