JavaScript 使用误区(如何在JavaScript中处理null和undefined?)
JavaScript 使用误区
赋值运算符应用错误
在 JavaScript 程序中如果你在 if 条件语句中使用赋值运算符的等号 (=) 将会产生一个错误结果, 正确的方法是使用比较运算符的两个等号 (==)。
if 条件语句返回 false (是我们预期的)因为 x 不等于 10:
var x = 0;
if (x == 10)
if 条件语句返回 true (不是我们预期的)因为条件语句执行为 x 赋值 10,10 为 true:
var x = 0;
if (x = 10)
if 条件语句返回 false (不是我们预期的)因为条件语句执行为 x 赋值 0,0 为 false:
var x = 0;
if (x = 0)
赋值语句返回变量的值。 |
比较运算符常见错误
在常规的比较中,数据类型是被忽略的,以下 if 条件语句返回 true:
var x = 10;
var y = \"10\";
if (x == y)
在严格的比较运算中,=== 为恒等计算符,同时检查表达式的值与类型,以下 if 条件语句返回 false:
var x = 10;
var y = \"10\";
if (x === y)
这种错误经常会在 switch 语句中出现,switch 语句会使用恒等计算符(===)进行比较:
以下实例会执行 alert 弹窗:
var x = 10;
switch(x) {
case 10: alert(\"Hello\");
}
以下实例由于类型不一致不会执行 alert 弹窗:
var x = 10;
switch(x) {
case \"10\": alert(\"Hello\");
}
加法与连接注意事项
加法是两个数字相加。
连接是两个字符串连接。
JavaScript 的加法和连接都使用 + 运算符。
接下来我们可以通过实例查看两个数字相加及数字与字符串连接的区别:
var x = 10 + 5; // x 的结果为 15
var x = 10 + \"5\"; // x 的结果为 \"105\"
使用变量相加结果也不一致:
var x = 10;
var y = 5;
var z = x + y; // z 的结果为 15
var x = 10;
var y = \"5\";
var z = x + y; // z 的结果为 \"105\"
浮点型数据使用注意事项
JavaScript 中的所有数据都是以 64 位浮点型数据(float) 来存储。
所有的编程语言,包括 JavaScript,对浮点型数据的精确度都很难确定:
var x = 0.1;
var y = 0.2;
var z = x + y // z 的结果为 0.3
if (z == 0.3) // 返回 false
我解决以上问题,可以用整数的乘除法来解决:
实例
var z = (x * 10 + y * 10) / 10; // z 的结果为 0.3
JavaScript 字符串分行
JavaScript 运行我们在字符串中使用断行语句:
实例 1
var x =
\"Hello World!\";
但是,在字符串中直接使用回车换行是会报错的:
实例 2
var x = \"Hello
World!\";
我们可以在选择开发工具或按下 F12 来查看错误信息:
字符串断行需要使用反斜杠(\\),如下所示:
实例 3
var x = \"Hello \\
World!\";
错误的使用分号
以下实例中,由于分号使用错误,if 语句中的代码块将无法执行:
if (x == 19);
{
// code block
}
Return 语句使用注意事项
JavaScript 默认是在代码的最后一行自动结束。
以下两个实例返回结果是一样的(一个有分号一个没有):
实例 1
function myFunction(a) {
var power = 10
return a * power
}
实例 2
function myFunction(a) {
var power = 10;
return a * power;
}
JavaScript 也可以使用多行来结束一个语句。
以下实例返回相同的结果:
实例 3
function myFunction(a) {
var
power = 10;
return a * power;
}
但是,以下实例结果会返回 undefined:
实例 4
function myFunction(a) {
var
power = 10;
return
a * power;
}
为什么会有这样的结果呢?因为在 JavaScript 中,实例 4 的代码与下面的代码一致:
function myFunction(a) {
var
power = 10;
return; // 分号结束,返回 undefined
a * power;}
解析
如果是一个不完整的语句,如下所示:
var
JavaScript 将尝试读取第二行的语句:
power = 10;
但是由于这样的语句是完整的:
return
JavaScript 将自动关闭语句:
return;
在 JavaScript 中,分号是可选的 。
由于 return 是一个完整的语句,所以 JavaScript 将关闭 return 语句。
注意:不用对 return 语句进行断行。 |
数组中使用名字来索引
许多程序语言都允许使用名字来作为数组的索引。
使用名字来作为索引的数组称为关联数组(或哈希)。
JavaScript 不支持使用名字来索引数组,只允许使用数字索引。
实例
var person = [];
person[0] = \"John\";
person[1] = \"Doe\";
person[2] = 46;
var x = person.length; // person.length 返回 3
var y = person[0]; // person[0] 返回 \"John\"
在 JavaScript 中, 对象 使用 名字作为索引。
如果你使用名字作为索引,当访问数组时,JavaScript 会把数组重新定义为标准对象。
执行这样操作后,数组的方法及属性将不能再使用,否则会产生错误:
实例
var person = [];
person[\"firstName\"] = \"John\";
person[\"lastName\"] = \"Doe\";
person[\"age\"] = 46;
var x = person.length; // person.length 返回 0
var y = person[0]; // person[0] 返回 undefined
定义数组元素,最后不能添加逗号
错误的定义方式:
points = [40, 100, 1, 5, 25, 10,];
正确的定义方式:
points = [40, 100, 1, 5, 25, 10];
定义对象,最后不能添加逗号
错误的定义方式:
websites = {site:\"菜鸟教程\", url:\"www.runoob.com\", like:460,}
正确的定义方式:
websites = {site:\"菜鸟教程\", url:\"www.runoob.com\", like:460}
Undefined 不是 Null
在 JavaScript 中, null 用于对象, undefined 用于变量,属性和方法。
对象只有被定义才有可能为 null,否则为 undefined。
如果我们想测试对象是否存在,在对象还没定义时将会抛出一个错误。
错误的使用方式:
if (myObj !== null && typeof myObj !== \"undefined\")
正确的方式是我们需要先使用 typeof 来检测对象是否已定义:
if (typeof myObj !== \"undefined\" && myObj !== null)
程序块作用域
在每个代码块中 JavaScript 不会创建一个新的作用域,一般各个代码块的作用域都是全局的。
以下代码的的变量 i 返回 10,而不是 undefined:
实例
for (var i = 0; i < 10; i++) {
// some code
}
return i;
如您还有不明白的可以在下面与我留言或是与我探讨QQ群308855039,我们一起飞!
如何在JavaScript中处理null和undefined?
在 JavaScript 的开发工作中,许多开发人员都头疼的一个问题就是处理可选值。怎样才能最大程度减少由 null、undefined,或在运行时未初始化的值所引发的错误,有哪些最佳策略呢?
有些语言针对这类情况有内置的解决方案。在某些静态类型的语言中,你可以认定 null 和 undefined 是非法值,并且让你的编程语言在编译时抛出 TypeError。但即使在这种语言中,也不能阻止 null 输入在运行时流入程序。
为了更好地处理这种问题,我们需要了解这些值的来源。以下是一些最常见的来源:
用户输入;
数据库 / 网络记录;
未初始化状态;
无法返回任何内容的函数。
用户输入
在处理用户输入时,验证是第一道也是最好的防线。我经常依靠 schema 验证器来完成这项工作。比如,你可以试试 react-jsonschema-form。
对输入的记录做 hydrate 处理
我总是会把从网络、数据库或用户输入中获得的输入传递给一个 hydrating 函数。例如,我会使用可以处理 undefined 值的 redux 动作创建者来 hydrate 用户记录:
1 2 3 4 5 6 7 8 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> setUser = ({ name = <span class="" style="color: #98c379;width: 79px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'Anonymous\'</span>, avatar = <span class="" style="color: #98c379;width: 72px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'anon.png\'</span> } = {}) => ({ <span class="" style="color: #c678dd;width: 29px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">type</span>: setUser.<span class="" style="color: #c678dd;width: 28px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">type</span>, payload: { name, avatar } }); setUser.<span class="" style="color: #c678dd;width: 28px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">type</span> = <span class="" style="color: #98c379;width: 150px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'userReducer/setUser\'</span>; |
有时,你需要根据数据的当前状态显示不同的内容。如果页面可以在所有数据初始化完毕之前显示,就可能会遇到这种情况。例如,当你向用户显示资金余额时,有时可能会在加载数据之前显示余额为零。这种事情我见过很多次,这会让用户感到不安。你可以创建一些自定义数据类型,这些数据类型根据当前状态生成不同的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> createBalance = ({ <span class="" style="color: #5c6370;width: 69px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// 默认状态</span> state = <span class="" style="color: #98c379;width: 108px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'uninitialized\'</span>, value = createBalance.empty } = {}) => createBalance.isValidState(state) && ({ __proto__: { uninitialized: <span class="" style="color: #abb2bf;width: 36px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 15px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">()</span> =></span> <span class="" style="color: #98c379;width: 28px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'--\'</span>, initialized: <span class="" style="color: #abb2bf;width: 36px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 15px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">()</span> =></span> value, format () { <span class="" style="color: #c678dd;width: 43px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">return</span> <span class="" style="color: #c678dd;width: 29px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">this</span>[<span class="" style="color: #c678dd;width: 29px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">this</span>.getState()](value); }, getState: <span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 15px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">()</span> =></span> state, <span class="" style="color: #c678dd;width: 22px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">set</span>: <span class="" style="color: #abb2bf;width: 58px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 36px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> { <span class="" style="color: #c678dd;width: 35px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> test = <span class="" style="color: #e6c07b;width: 44px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">Number</span>(value); assert(!<span class="" style="color: #e6c07b;width: 43px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">Number</span>.isNaN(test), <span class="" style="color: #98c379;width: 273px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">`setBalance Invalid value: <span class="" style="color: #e06c75;width: 72px;text-decoration: none solid #e06c75;font-weight: 400;font-style: normal">${ value }</span>`</span>); <span class="" style="color: #c678dd;width: 43px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">return</span> createBalance({ state: <span class="" style="color: #98c379;width: 93px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'initialized\'</span>, value }); } } }); createBalance.empty = <span class="" style="color: #98c379;width: 22px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'0\'</span>; createBalance.isValidState = <span class="" style="color: #abb2bf;width: 57px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">state</span> =></span> { <span class="" style="color: #c678dd;width: 15px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">if</span> (![<span class="" style="color: #98c379;width: 107px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'uninitialized\'</span>, <span class="" style="color: #98c379;width: 93px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'initialized\'</span>].includes(state)) { <span class="" style="color: #c678dd;width: 35px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">throw</span> <span class="" style="color: #c678dd;width: 22px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">new</span> <span class="" style="color: #e6c07b;width: 35px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">Error</span>(<span class="" style="color: #98c379;width: 294px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">`createBalance Invalid state: <span class="" style="color: #e06c75;width: 71px;text-decoration: none solid #e06c75;font-weight: 400;font-style: normal">${ state }</span>`</span>); } <span class="" style="color: #c678dd;width: 44px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">return</span> <span class="" style="color: #56b6c2;width: 29px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">true</span>; }; <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> setBalance = <span class="" style="color: #abb2bf;width: 57px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 36px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> createBalance().set(value); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> emptyBalanceForDisplay = createBalance() .format(); <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(emptyBalanceForDisplay); <span class="" style="color: #5c6370;width: 50px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// \'--\'</span> <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> balanceForDisplay = setBalance(<span class="" style="color: #98c379;width: 29px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'25\'</span>) .format(balance); <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(balanceForDisplay); <span class="" style="color: #5c6370;width: 50px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// \'25\'</span> <span class="" style="color: #5c6370;width: 260px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// 取消下列调用的注释前缀就能看到错误示例:</span> <span class="" style="color: #5c6370;width: 437px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// setBalance(\'foo\'); // Error: setBalance Invalid value: foo</span> <span class="" style="color: #5c6370;width: 402px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// Error: createBalance Invalid state: THIS IS NOT VALID</span> <span class="" style="color: #5c6370;width: 437px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// createBalance({ state: \'THIS IS NOT VALID\', value: \'0\' });</span> |
上面的代码是一个状态机,其设计无法显示无效状态。首次创建余额数字时,它将被设置为一个 unintitialized 状态。如果你尝试在 uninitialized 状态时显示余额,则只会获得一个占位符值(“--”)。要调整这个设置,你必须调用.set 方法,或调用我们在 createBalance 下面定义的 setBalance 捷径来显式设置一个值。
该状态本身经过封装,以保护其免受外界干扰,这样其他函数就无法捕获它并将其设置为无效状态了。
注意:想知道为什么我们要使用字符串而不是数字吗?那是因为我用了精度很高的大数字符串来表示货币类型,以避免舍入错误,并能准确地表示加密货币交易中的数值(这类交易中的数值精度要求可能会非常高)。
如果你使用 Redux 或 Redux 架构,则可以使用 Redux-DSM 来声明状态机。
避免创建 null 和 undefined 值
在你自己的函数中,你可以尽量避免创建 null 或 undefined 值。我想到了很多 JavaScript 的内置方法来做到这一点,见下文。
避免 null
我从未在 JavaScript 中显式创建 null 值,因为我觉得用两个不同的原始值来表示\"这个值不存在\",实在是没什么意义的事情。
自 2015 年开始 JavaScript 就支持默认值了,当你没有为相关参数或属性提供值时,它们就会填入默认值。这些默认值不适用于 null 值。根据我的经验,这通常会导致一个错误。为了避免这种陷阱,请不要在 JavaScript 中使用 null。
如果你希望处理未初始化的值或空值这类特殊情况,状态机是更好的选择,如前所述。
新的 JavaScript 功能
有几个功能可以帮助你处理 null 或 undefined 值。在撰写本文时,下面两个功能都是第 3 阶段的提案,将来你看到本文时这两个功能可能已经正式发布了。
目前,可选链(optional chaining)是第 3 阶段的提案。它的工作机制是这样的:
1 2 3 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> foo = {}; <span class="" style="color: #5c6370;width: 315px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// console.log(foo.bar.baz); // throws error</span> console.<span class="" style="color: #e6c07b;width: 21px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">log</span>(foo.bar?.baz) <span class="" style="color: #5c6370;width: 86px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// undefined</span> |
空位合并运算符
这也是准备添加到规范中的第 3 阶段提案,“空位合并运算符(Nullish Coalescing Operator)”基本上是“回退值运算符”的一种高大上的说法。如果左侧的值是 undefined 或 null,则其会等于右侧的值。它的工作机制是这样的:
1 2 3 4 5 6 7 |
<span class="" style="color: #c678dd;width: 22px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">let</span> baz; <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(baz); <span class="" style="color: #5c6370;width: 86px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// undefined</span> <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(baz ?? <span class="" style="color: #98c379;width: 94px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'default baz\'</span>); <span class="" style="color: #5c6370;width: 101px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// default baz</span> <span class="" style="color: #5c6370;width: 244px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// Combine with optional chaining:</span> <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(foo.bar?.baz ?? <span class="" style="color: #98c379;width: 94px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'default baz\'</span>); <span class="" style="color: #5c6370;width: 101px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// default baz</span> |
目前提案尚未正式进入规范,所以你需要安装 @babel/plugin-proposal-optional-chaining 和 @ babel/plugin-proposal-nullish-coalescing-operator。
使用 Promise 实现异步 Either
如果某个函数可能不返回值,则最好将其包装在一个 Either 中。在函数式编程中,Either monad 是一种特殊的抽象数据类型,它允许你附加两个不同的代码路径:成功路径或失败路径。JavaScript 具有内置的异步 Either monad-ish 数据类型,称为 Promise。你可以用它对 undefined 值进行声明式错误分支:
1 2 3 4 5 6 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> exists = <span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x != <span class="" style="color: #56b6c2;width: 28px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">null</span>; <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> ifExists = <span class="" style="color: #abb2bf;width: 58px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 36px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> exists(value) ? <span class="" style="color: #e6c07b;width: 50px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">Promise</span>.resolve(value) : <span class="" style="color: #e6c07b;width: 50px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">Promise</span>.reject(<span class="" style="color: #98c379;width: 194px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">`Invalid value: <span class="" style="color: #e06c75;width: 71px;text-decoration: none solid #e06c75;font-weight: 400;font-style: normal">${ value }</span>`</span>); ifExists(<span class="" style="color: #56b6c2;width: 29px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">null</span>).then(log).catch(log); <span class="" style="color: #5c6370;width: 157px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// Invalid value: null</span> ifExists(<span class="" style="color: #98c379;width: 51px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'hello\'</span>).then(log).catch(log); <span class="" style="color: #5c6370;width: 57px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// hello</span></code>你可以根据需要编写一个同步版本,但这里我还用不到那一步,就留给你做练习吧。如果你在 functor 和 monad 方面有良好的基础,那么这个过程会很容易。如果这听起来很吓人,那也不用担心,只用 Promise 即可。它们是内置的,并且在大多数情况下都可以正常工作。 |
使用数组实现 Maybe
数组实现了一个 map 方法,这个方法会使用一个函数应用在数组的每个元素上。如果数组为空,则这个函数永远不会被调用。换句话说,JavaScript 中的数组可以充当 Haskell 等语言中的 Maybe 角色。
Maybe 是什么?
Maybe 是一种特殊的抽象数据类型,它封装了一个可选值。数据类型有两种形式:
Just——包含一个值的 Maybe;
Nothing——没有值的 Maybe。
下面是具体的机制:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> log = <span class="" style="color: #abb2bf;width: 29px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> <span class="" style="color: #e6c07b;width: 50px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(x); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> exists = <span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x != <span class="" style="color: #56b6c2;width: 28px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">null</span>; <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> Just = <span class="" style="color: #abb2bf;width: 57px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> ({ map: <span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">f</span> =></span> Just(f(value)), }); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> Nothing = <span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 14px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">()</span> =></span> ({ map: <span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 14px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">()</span> =></span> Nothing(), }); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> Maybe = <span class="" style="color: #abb2bf;width: 57px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> exists(value) ? Just(value) : Nothing(); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> empty = <span class="" style="color: #56b6c2;width: 65px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">undefined</span>; Maybe(empty).map(log); <span class="" style="color: #5c6370;width: 107px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// does not log</span></code> 这只是一个示例,用来演示这个概念。你可以围绕 maybe 建立一整套有用的函数库,实现 flatMap 和 flat 之类的操作(例如,在编写多个返回 Maybe 的函数时避免 Just(Just(value)) 这种情况)。但是 JavaScript 已经有一种数据类型可以直接实现这些功能,因此我通常会这样做:使用数组。 |
如果你要创建一个可能会,或可能不会产生结果的函数(尤其是可能有多个结果的情况下),那么这种情况下最好的方法可能就是返回一个数组。
1 2 3 4 5 6 |
<span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> log = <span class="" style="color: #abb2bf;width: 29px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> <span class="" style="color: #e6c07b;width: 50px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(x); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> exists = <span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x != <span class="" style="color: #56b6c2;width: 28px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">null</span>; <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> arr = [<span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">1</span>,<span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">2</span>,<span class="" style="color: #d19a66;width: 6px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">3</span>]; <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> find = <span class="" style="color: #abb2bf;width: 86px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">(<span class="" style="color: #abb2bf;width: 50px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">p, list</span>) =></span> [list.find(p)].filter(exists); find(<span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x > <span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">3</span>, arr).map(log); <span class="" style="color: #5c6370;width: 172px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// does not log anything</span> find(<span class="" style="color: #abb2bf;width: 28px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x < <span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">3</span>, arr).map(log); <span class="" style="color: #5c6370;width: 65px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// logs 1</span> |
我发现在空列表上不会调用 map,这对避免 null 和 undefined 值来说非常有用,但是请记住,如果数组包含 null 和 undefined 值,它将使用这些值调用该函数,因此如果你在运行的函数可能会产生 null 或 undefined,你需要将其从返回的数组中过滤出来,如上所示。这可能会改变集合的长度。
在 Haskell 中,有一个函数 maybe(就像 map 一样)将一个函数应用于一个值上。但是该值是可选的,并封装在 Maybe 中。我们可以使用 JavaScript 的 Array 数据类型做基本上相同的事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<span class="" style="color: #5c6370;width: 258px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// maybe = b => (a => b) => [a] => b</span> <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> maybe = <span class="" style="color: #abb2bf;width: 194px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">(<span class="" style="color: #abb2bf;width: 157px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">fallback, f = () => {}</span>) =></span> arr => arr.map(f)[<span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">0</span>] || fallback; <span class="" style="color: #5c6370;width: 380px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// turn a value (or null/undefined) into a maybeArray</span> <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> toMaybeArray = <span class="" style="color: #abb2bf;width: 57px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 35px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">value</span> =></span> [value].filter(exists); <span class="" style="color: #5c6370;width: 345px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// maybe multiply the contents of an array by 2,</span> <span class="" style="color: #5c6370;width: 265px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// default to 0 if the array is empty</span> <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> maybeDouble = maybe(<span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">0</span>, <span class="" style="color: #abb2bf;width: 29px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal"><span class="" style="color: #abb2bf;width: 7px;text-decoration: none solid #abb2bf;font-weight: 400;font-style: normal">x</span> =></span> x * <span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">2</span>); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> emptyArray = toMaybeArray(<span class="" style="color: #56b6c2;width: 28px;text-decoration: none solid #56b6c2;font-weight: 400;font-style: normal">null</span>); <span class="" style="color: #c678dd;width: 36px;text-decoration: none solid #c678dd;font-weight: 400;font-style: normal">const</span> maybe2 = toMaybeArray(<span class="" style="color: #d19a66;width: 7px;text-decoration: none solid #d19a66;font-weight: 400;font-style: normal">2</span>); <span class="" style="color: #5c6370;width: 287px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// logs: \"maybeDouble with fallback: 0\"</span> <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(<span class="" style="color: #98c379;width: 208px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'maybeDouble with fallback: \'</span>, maybeDouble(emptyArray)); <span class="" style="color: #5c6370;width: 244px;text-decoration: none solid #5c6370;font-weight: 400;font-style: italic">// logs: \"maybeDouble(maybe2): 4\"</span> <span class="" style="color: #e6c07b;width: 51px;text-decoration: none solid #e6c07b;font-weight: 400;font-style: normal">console</span>.log(<span class="" style="color: #98c379;width: 165px;text-decoration: none solid #98c379;font-weight: 400;font-style: normal">\'maybeDouble(maybe2): \'</span>, maybeDouble(maybe2)); |
maybe 需要一个回退值,然后是一个映射到 maybe 数组上的函数,然后是一个 maybe 数组(包含一个值,或者为空的数组),最后返回将该函数应用于数组内容的结果,或者在数组为空时返回回退值。为了方便起见,我还定义了 toMaybeArray 函数,并 curry 了 maybe 函数来让它更显眼一些,方便展示。
如果你想在生产代码中执行类似的操作,我已经创建了一个经过单元测试的开源库,可以简化你的工作。这个库叫 Maybearray。与其他 JavaScript Maybe 库相比,Maybearray 的优势在于它使用原生 JavaScript 数组来表示值,因此你不必对其进行任何特殊处理,也用不着来回转换。
1. 带 [亲测] 说明源码已经被站长亲测过!
2. 下载后的源码请在24小时内删除,仅供学习用途!
3. 分享目的仅供大家学习和交流,请不要用于商业用途!
4. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
5. 本站所有资源来源于站长上传和网络,如有侵权请邮件联系站长!
6. 没带 [亲测] 代表站长时间紧促,站长会保持每天更新 [亲测] 源码 !
7. 盗版ripro用户购买ripro美化无担保,若设置不成功/不生效我们不支持退款!
8. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
9. 如果你也有好源码或者教程,可以到审核区发布,分享有金币奖励和额外收入!
10.如果您购买了某个产品,而我们还没来得及更新,请联系站长或留言催更,谢谢理解 !
GG资源网 » JavaScript 使用误区(如何在JavaScript中处理null和undefined?)