javascript语句中加入空字符串有什么用
What is the usage of adding an empty string in a javascript statement
我看到许多 JavaScript 语句中使用了一个空字符串(''
或 ""
),但不确定它代表什么。
例如var field = current.condition_field + '';
有人可以澄清一下吗?
类型转换。
它将类型转换为 string
如果变量 current.condition_field
不是 string
类型,通过在 end/beginning 处使用 +
运算符添加 ''
将其转换为 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 on string prototype
) on that variable.
(myVar + '').toLowerCase();
我看到许多 JavaScript 语句中使用了一个空字符串(''
或 ""
),但不确定它代表什么。
例如var field = current.condition_field + '';
有人可以澄清一下吗?
类型转换。
它将类型转换为 string
如果变量 current.condition_field
不是 string
类型,通过在 end/beginning 处使用 +
运算符添加 ''
将其转换为 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();