Iterative conditional removal of object property using 'for..in' and 'if' [duplicate]

依然范特西╮ 提交于 2019-12-31 05:16:10

问题


function removeNumbersLargerThan(num, obj) {
  for (var key in obj) {
    if (!isNaN(obj[key]) && obj[key] > num) {
      delete obj.key;
    }
  }
  return obj;
}
var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // Should be {b: 2, c: 'montana'}
The function should remove any property that meets the 'if' condition inside the 'for' loop, but it doesn't.

回答1:


You miss the square brackets, while defining the object key to delete.

function removeNumbersLargerThan(num, obj) {
  for (var key in obj) {
    if (!isNaN(obj[key]) && obj[key] > num) {
      delete obj[key];
    }
  }
  return obj;
}
var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // Should be {b: 2, c: 'montana'}



回答2:


You should replace delete obj.key; with delete obj[key];



来源:https://stackoverflow.com/questions/43615295/iterative-conditional-removal-of-object-property-using-for-in-and-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!