以下为loadsh源码中的一段:
function baseCompareAscending(value, other) {
if (value !== other) {
var valIsReflexive = value === value,
othIsReflexive = other === other;
if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) {
return 1;
}
if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) {
return -1;
}
}
return 0;
}
比较大小。
问题一, 代码写法问题, 为什么不写成下面代码这种形式,在我看来两种写法是等价的,但是下面的精简了一层{}
,上面的那个写法我没有看出其他的含义
function baseCompareAscending(value, other) {
if (value === other) return 0;
var valIsReflexive = value === value,
othIsReflexive = other === other;
if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) {
return 1;
}
if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) {
return -1;
}
}
问题2:
除了NaN的情况外,是否还存在 value === value 为 false的情况?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如 @limichange 所述,后面一种写法没有完整覆盖所有情况,一个简单的例子是涉及对象的时候
baseCompareAscending({},{})关于
a === a //false的情况确实只有NaN一种可能,可以看看ECMA标准中关于严格比较的描述。在类型和值都相同的条件下只有NaN会返回false在我看来两种写法是等价的,,但是下面的精简了一层{}
是等价的。你的做法,在重构一书中被成为 Guard clause,是一种常见的重构方法。
从代码质量看,被重构领域认为是更好的代码。也更加符合契约编程的精神。
{显然,我弄错了。多谢指正}
"{} ~== {} " ,防不胜防。
为什么不写成下面代码这种形式
高手也有小毛病。笨蛋也非无处不可取。重构业界认可的,也并非定论。在小圈子内,可以通过代码标准的方式约定。大圈子内,做此事带来的纷争甚多,得不偿失。