Javascript 将空字符串添加到parseInt的第一个参数
我只是想了解JS咖喱是如何工作的。当我在寻找它时,我发现了一个相关的例子:Javascript 将空字符串添加到parseInt的第一个参数,javascript,Javascript,我只是想了解JS咖喱是如何工作的。当我在寻找它时,我发现了一个相关的例子: var add = function (orig) { var inner = function (val) { return add(parseInt(val+'', 10) == val ? inner.captured+val : inner.captured); }; inner.captured = orig; inner.valueOf = function () {return in
var add = function (orig) {
var inner = function (val) {
return add(parseInt(val+'', 10) == val ? inner.captured+val : inner.captured);
};
inner.captured = orig;
inner.valueOf = function () {return inner.captured;};
return inner;
};
向中的第一个参数添加空字符串有什么意义
方法?
我认为它也可能与将表达式转换为字符串有关
快速测试以显示发生了什么:
typeof(1)
"number" // value is 1 (number)
typeof(1+'')
"string" // now value is "1" (a string)
把它做成绳子的目的是什么
其目的可能是避免本机代码调用abstractToString
方法将parseInt
的第一个参数转换为字符串
我们可以在MDN中看到,parseInt
的第一个参数是字符串,描述如下:
要分析的值。如果字符串不是字符串,则将其转换为
字符串(使用ToString抽象操作)。前导空格
将忽略字符串中的
为了解释,我们可以重新编写部分代码:
return add(parseInt(val+'', 10) == val ? inner.captured+val : inner.captured);
// could be written like:
if ( parseInt(val+'', 10) == val ) {
return inner.captured+val
}
else {
return inner.captured;
}
// Looking at:
parseInt(val+'', 10) == val
// we're checking if the number at base 10 is equal to itself
// parseInt takes a string as it's first parameter, hence
// the type-casting with +''.
// This step could probably be ignored as the docs say that the number is
// cast to a string automatically, however for completeness we might
// choose to manually cast it.
你是说咖喱吗?@epascarello yeap,对不起,我弄错了。它将第一个参数强制为字符串。但是,这是不必要的,因为它将被
parseInt
本身转换为字符串,但将其转换为parseInt字符串的目的是什么?我明白了,对我来说足够清楚了,谢谢!很有趣moment@WouterHuysentruit(首先,这不是一个打字问题)第二,我让回答者实际回答这个问题。谢谢你的解释!