将空字符串添加到parseInt的第一个参数

时间:2015-11-24 13:49:15

标签: javascript

我只是想了解JS currying的工作原理。在我找的时候,我找到了一个相关的例子:

openWindow("/contact",function(firstname, lastname){
    this.alert("Hello "+firstname+" "+lastname);
}, "John", "Doe");

将空字符串添加到 parseInt 中的第一个参数有什么意义 方法? 我认为它也可能与valueOf

有关

2 个答案:

答案 0 :(得分:5)

val+''将表达式转换为字符串。

快速测试以显示正在进行的操作:

typeof(1)
"number" // value is 1 (number)
typeof(1+'')
"string" // now value is "1" (a string)
  

使它成为字符串的目的是什么?

目的可能是避免本机代码调用抽象ToString方法将parseInt的第一个参数转换为字符串。

我们可以在MDN中读到parseInt的第一个参数是带有以下描述的字符串:

  

要解析的值。如果string不是字符串,则将其转换为   一个字符串(使用ToString抽象操作)。领先的空白   在字符串中被忽略。

答案 1 :(得分:1)

要解释我们可以重写部分代码:

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.

parseInt docs