简体   繁体   English

forEach中的箭头函数中的三元运算符

[英]ternary operator inside an arrow function inside forEach

I have this little function that is supposed to remove object properties with even values. 我有这个小功能,应该删除具有偶数值的对象属性。

function removeEvenValues(obj) {
  Object.keys(obj).forEach(k => ((!isNaN(obj[k])) && (obj[k] % 2 === 0)) ? delete obj[k] : k);
}

In the else {} part of the ternary operator, how do I leave it empty like in an if (true){ doSomething();} kind of construct? 在三元运算符的else {}部分中,如何像if (true){ doSomething();}这种构造那样将其留空? Or does it even make sense to use a fat arrow function in this case? 还是在这种情况下使用粗箭头功能甚至有意义?

Yes, you shouldn't use a concise arrow function or a ternary operator here. 是的,您不应该在这里使用简洁的箭头功能或三元运算符。 Well, you could use && instead of the ternary , but you really shouldn't. 好吧,您可以使用&& 代替三元数 ,但实际上不应该这样做。

You shouldn't even use forEach in ES6 - just use a proper loop: 应该甚至不使用forEach在ES6 -只需使用一个适当的循环:

function removeEvenValues(obj) {
  for (const k of Object.keys(obj))
    if (!isNaN(obj[k]) && obj[k] % 2 === 0)
      delete obj[k];
}

or (as you probably don't care about inherited properties) 或(因为您可能不关心继承的属性)

function removeEvenValues(obj) {
  for (const k in obj)
    if (!isNaN(obj[k]) && obj[k] % 2 === 0)
      delete obj[k];
}

There is nothing wrong with using a fat arrow, as it is a function expression, but because you are not returning a value, you shouldn't use a ternary operator. 使用粗箭头并没有错,因为它是一个函数表达式,但是因为您没有返回值,所以不应该使用三元运算符。 You can do: 你可以做:

function removeEvenValues(obj) {
    Object.keys(obj).forEach(k => {if(!isNaN(obj[k]) && (obj[k] % 2 === 0)) {delete obj[k]}});
}

You could use a logical AND && and remove some superfluous parentheses. 您可以使用逻辑AND &&并删除一些多余的括号。

 function removeEvenValues(obj) { Object.keys(obj).forEach(k => !isNaN(obj[k]) && obj[k] % 2 === 0 && delete obj[k]); } var o = { foo: 41, bar: 42 }; removeEvenValues(o); console.log(o); 

As Nina wrote, you can use logical operators instead of the ternary operator. 正如Nina所写,可以使用逻辑运算符代替三元运算符。 You can also turn the condition around and use || 您也可以扭转条件并使用|| .

Be aware though what isNaN returns. 请注意,虽然isNaN返回了。 For instance isNaN([2]) === false ! 例如isNaN([2]) === false So instead you might want to test for the primitive number type with typeof . 因此,您可能需要使用typeof测试原始数字类型。

Finally, recently the Object.entries method has found its way in some browsers, and in this case it can be nice to use instead of Object.keys : 最后,最近Object.entries方法已在某些浏览器中找到了方法,在这种情况下,最好使用它代替Object.keys

 function removeEvenValues(o) { Object.entries(o).forEach(([k, v]) => typeof v != "number" || v % 2 || delete o[k]); } // Sample var obj = { "a": 2, "b": "hello", "c": [4], "d": 5, "e": 6 }; removeEvenValues(obj); console.log(obj); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM