问题
我正在从 JavaScript 函数中推送值并用对象填充数组。 我想要发生的是删除零的键+值对。
返回数组的示例
[Object percent: 516 unit: -10.689124404913258
Object percent: 516 unit: -9.011227255423254
Object percent: 561 unit: -12.669770888525518
Object percent: 6516 unit: -15.99180968320506
Object percent: 0 unit: 0]
JavaScript
my_arr = []
for(var i = my_arr.length - 1; i >= 0; i--) {
if(array[i] === 0) {
array.splice(i, 1);
}
return my_arr;
}
最佳答案
如果您想从数组中删除具有价格和单位的项目,您可以使用它。
var items = [
{ percent: 516, unit: -10.689124404913258 },
{ percent: 516, unit: -9.011227255423254 },
{ percent: 561, unit: -12.669770888525518 },
{ percent: 6516, unit: -15.99180968320506 },
{ percent: 0, unit: 0 }
];
items = items.filter(i => i.percent && i.unit);
console.log(items);
顺便说一句你的主要问题是你返回到循环内,这将在第一回合停止循环。
我什至不相信你的代码能工作一段时间,因为在函数范围之外使用 return
我会犯一种错误:
Uncaught SyntaxError: Illegal return statement
关于javascript - 从对象数组中删除零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38489745/