What does this Javascript line do? [duplicate]

旧时模样 提交于 2019-12-13 07:28:17

问题


Possible Duplicate:
What is “var _gaq = _gaq || []; ” for ?

var _gaq = _gaq || [];

I'm not sure what this line is doing? Can someone explain this to me?


回答1:


This is similar to doing

var _gaq = _gaq ? : _gaq : [];

It means that if _gaq is set, it'll set it to _gaq, otherwise it will default to a new empty array.

  • var means it's local scope
  • _gaq is the name of the variable
  • || means or

It's saying that if _gaq doesn't already exist, set it to a new array which is what [] means.




回答2:


It declares a variable named _gaq. If that variable was already defined, and is a truthy value, then the line is equivalent to writing

var _gaq = _gaq;

If _gaq is a falsy value, then the newly declare variable is an empty array.

Some reference on truthiness and falsiness in JavaScript:

  • http://11heavens.com/falsy-and-truthy-in-javascript
  • http://javascript.crockford.com/style2.html



回答3:


It checks if _gaq is defined if not assigns an array object to _gaq.

its equivalent to

if(!_gaq){
 var _gaq = [];
}


来源:https://stackoverflow.com/questions/5643740/what-does-this-javascript-line-do

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