避免对“空”变量使用null或未定义?

时间:2019-08-29 02:11:15

标签: javascript arrays object ecmascript-6

我看到了这段代码

{
    "working_dir": "${folder:${project_path:${file_path}}}",
    "selector": "source.cs",

    "variants":
    [
        {
            "name": "Build",
            "shell_cmd": "dotnet build",
            "word_wrap": false,
            "quiet": true,
        },
        {
            "name": "Clean",
            "shell_cmd": "dotnet clean"
        },
        {
            "name": "Run",
            "shell_cmd": "dotnet run"
        },
        {
            "name": "Run Interactive",
            "cmd": ["dotnet", "run"],
            "target": "terminus_open",
            "auto_close": false,
        }
    ],
}

这让我想知道为什么作者使用 recipient(message) { return users.find(u => u.id === message.recipient) || null; } 进行回退,而排除回退是什么问题呢?

2 个答案:

答案 0 :(得分:0)

因为默认情况下find如果找不到项目,则返回undefined-用户定义的返回方法也有多种。 null用作指示未找到该项目,但返回值的信号。

或者,您可以返回一个空对象:

return users.find(({ id }) => id === message.recipient) || {};

答案 1 :(得分:0)

return users.find(u => u.id === message.recipient)

find在未找到任何值的情况下返回未定义,因此,如果使用返回值的逻辑仅检查null或在没有值的情况下需要将null作为默认值找到了,所以这显然取决于您使用返回值的逻辑方式