我看到许多 JavaScript 语句中使用了一个空字符串(''
或 ""
),但不确定它代表什么。
例如var field = current.condition_field + '';
有人可以澄清一下吗?
最佳答案
类型转换。
它将类型转换为 string
如果变量 current.condition_field
不是 string
类型,通过使用 +
运算符添加 ''
它的结尾/开头将其转换为 string
。
var field = current.condition_field + '';
因此,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);
感谢@KJPrice:
This is especially useful when you want to call a
string
method(Method defined onstring prototype
) on that variable.
(myVar + '').toLowerCase();
关于javascript - javascript语句中加入空字符串有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30980931/