[英]Why does the '+=' operator return undefined?
當我准備一個函數時,我注意到它最初返回“未定義”以及應該返回的其他信息。 這是該功能 :
foo = function(bar) {
var glorp;
if(typeof bar == 'undefined'){bar = 'baz'}; // there will be other conditions later
if('baz' == bar) {
glorp += 'this, ';
glorp += 'that, ';
glorp += 'the other';
return glorp;
}
}
我正在這樣調用函數:
$('#glorp').append(foo());
返回是這樣的:
undefinedthis,that,另一個
當我期望這個:
這個,那個,另一個
我做了很多挖掘工作,但找不到任何確定的東西。 然后,我將第一個glorp
運算符更改為just =
,並且未定義的消息消失了。
因為glorp
是在函數的開頭聲明的,所以應該在if
語句中定義它,並且看來是因為'this'成功返回了。
返回什么是“未定義”?
因為
var glorp; //<--undefined
console.log(glorp); //logs undefined
glorp = glorp + "x"; // undefined + "x" -> "undefined" + "x" -> "undefinedx"
console.log(glorp); //logs "undefinedx"
將其設置為空字符串
var glorp = "";
您需要在開始時將glorp
一個空字符串
var glorp = "";
對於您的輸出,當您添加undefined + string
它將使undefined
成為字符串值"undefined"
。 所以"undefined" + "this" = "undefinedthis"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.