在javascript语句中添加空字符串的用法是什么?

use*_*643 6 javascript string concatenation

我看到许多JavaScript语句中使用了一个空字符串(''""),但不确定它代表什么.

例如 var field = current.condition_field + '';

有人可以澄清一下吗?

Tus*_*har 13

类型铸造.它将类型转换为string

如果变量current.condition_field不是string类型,则通过在结尾/开头添加''using +运算符将其转换为string.

var field = current.condition_field + ''; 
Run Code Online (Sandbox Code Playgroud)

所以,field永远string.

var bool = true; // Boolean
var str = bool + ''; // "true"

document.write('bool: ' + typeof bool + '<br />str: ' + typeof str);


var num = 10; // Numeric
var str = num + ""; // "10"

document.write('<br /><br />num: ' + typeof num + '<br />str: ' + typeof str);
Run Code Online (Sandbox Code Playgroud)

感谢@KJPrice:

当您想要在该变量string上调用方法(定义方法string prototype)时,这尤其有用.

(myVar + '').toLowerCase();
Run Code Online (Sandbox Code Playgroud)

  • 当您计划对变量使用String方法时,这尤其有用:`(someVariable +'').toUpperCase()` (3认同)