【问题标题】:Best practice using null in a ternary operator in JavaScript在 JavaScript 的三元运算符中使用 null 的最佳实践
【发布时间】:2021-07-12 01:00:55
【问题描述】:

嘿,第一次发帖/用户,我一直在进行一些编码练习。我写了一段通过测试的代码,但我不确定这是否是最佳实践

在这个示例中,我使用 filter 函数迭代一个数组。我正在使用一个回调函数,它将返回长度大于 5 的单词。

示例代码

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

const interestingWords = words.filter(word => {
    return word ? word.length > 5 : null
})

在我看来,如果条件不满足,它甚至不应该尝试返回。当我返回 null 时会发生什么?或者这是我根本不会使用三元的情况。

我得到的最好的来自 MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

值 null 用文字写入:null。 null 不是全局对象属性的标识符,就像 undefined 一样。相反,null 表示缺乏标识,表示变量不指向任何对象。在 API 中,通常在可以预期对象但没有相关对象的地方检索到 null。

那么我应该避免在这种情况下返回 null 吗?

【问题讨论】:

  • words.filter(word=>word.length>5);

标签: javascript


【解决方案1】:

所有.filter 的回调关心的是它内部返回的真值或假值。在这里,最好直接返回那个比较,不需要条件运算符:

const interestingWords = words.filter(word => word.length > 5);

类似的结构

return word ? word.length > 5 : null

如果您需要检查一个子属性,这可能是有意义的,但前提是数组元素首先存在,例如:

const objects = [
  null,
  { word: 'foo' },
  { word: 'barbar' },
  null
];

const interestingObjects = objects.filter(
  obj => obj ? obj.word.length > 5 : null
);
console.log(interestingObjects);

【讨论】:

    【解决方案2】:

    如果数组的元素可能是nullundefined,您可以使用可选的链接运算符。

    const interestingWords = words.filter(word => {
        return word?.length > 5
    })
    

    【讨论】:

    • 你知道我以前在 SWIFT 中看到过链接。感谢您的反馈,我需要更加熟悉它
    猜你喜欢
    • 2015-07-02
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    相关资源
    最近更新 更多