如果未声明 ga ,则javascript语句下方会导致错误。
if (ga)
{
alert(ga);
}
错误是:
ga is not defined
看起来未声明的变量在bool表达式中无法识别。那么,为什么以下声明有效?
var ga = ga || [];
对我来说,ga在“||”之前被视为bool值。如果是假,则在“||”之后表达被分配到最终的ga。
答案 0 :(得分:4)
null或定义的是javascript中的falsey值(隐式计算为false。)|| operator返回第一个未计算为false的值。
var x = 0 || "" || null || "hello" || false; // x equals "hello"
另一方面&& operator将返回第一个falsey值或最后一个值。
var y = "a string" && {"attr":"an object"} && false && ["array"];
// y equals false
var z = "a string" && {"attr":"an object"} && ["array"];
// z equals ["array"]
答案 1 :(得分:3)
修改:您需要先使用var ga;
或var ga = ga || [];
,因为它首先声明ga并为其指定值。
你可以试试这个
var x = 1, y = x + 1;
alert([x,y]) // 1,2
您可能会注意到,当y被声明时,x已经被声明并且已经为其分配了1。
因此,在您的情况下,当ga || []
分配时,已经声明了ga及其有效变量。
答案 2 :(得分:1)
这适用于'var'的情况,因为创建了范围分辨率中的变量停止。 如果没有'var',你只需要查看范围链,就会被告知。如果确实希望使用全局变量:
// This is fine because assignment always sets a property value
// in this case (no 'var ga') it's the same as window.ga = window.ga || []
ga = window.ga || []
或者:
// Once again, only the lookup is affected with "running off"
// the lookup chain. It's not that the variable has no value --
// the problem is there IS NO VARIABLE.
if (!window.ga) {
ga = []
}
甚至这个:
// First line is the same as window.ga = window.ga,
// but now the property ga is guaranteed to exist on the window object --
// the VALUE of the property may (still) be undefined
ga = window.ga
ga = ga || []
请注意,在这两种情况下,我都明确地将ga
作为window
(全局)对象的属性调用。
您可以在此处阅读详细信息:Identifier Resolution, Execution Contexts and Scope Chains。
范围内var的放置无关紧要。以下所有内容都是相同的:
var ga
ga = ga || []
var ga = ga || []
ga = ga || []
var ga
答案 3 :(得分:1)
可能看起来不那么奇怪:
if (typeof ga !== 'undefined')
{
alert(ga);
}
答案 4 :(得分:0)
在第二个语句中,检查ga是否已定义,如果为true,则为其自身分配。否则,它被赋予一个空值。
答案 5 :(得分:0)
你期待b成为一个数组, 可能你想在b上使用数组方法 或从中读取索引值。
var b= s.match(/\d+/) || [];
return b[0];
返回匹配的文本或未定义 -
没有空数组赋值,如果没有匹配则第二行会抛出错误。