What is the usage of adding an empty string in a javascript statement

拈花ヽ惹草 提交于 2019-12-01 02:46:53

问题


I see an empty string ('' or "") used in many JavaScript statements but not sure what does it stand for.

e.g. var field = current.condition_field + '';

Can someone please clarify?


回答1:


Type Casting. It converts the type to string

If variable current.condition_field is not of string type, by adding '' using + operator at the end/beginning of it converts it to string.

var field = current.condition_field + ''; 

So, field is always string.

Example

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);

Thanks to @KJPrice:

This is especially useful when you want to call a string method(Method defined on string prototype) on that variable.

(myVar + '').toLowerCase();


来源:https://stackoverflow.com/questions/30980931/what-is-the-usage-of-adding-an-empty-string-in-a-javascript-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!