JavaScript: Testing variables for undefined value; testing whether object is array

怎甘沉沦 提交于 2019-12-10 08:45:55

问题


  1. Is there a difference between typeof value === "undefined" and value === undefined?

  2. Why did JavaScript need Array.isArray() in ECMAScript 5? Can't I just call value instanceof Array to determine whether an given variable is an array?


回答1:


//var value; There is no var declaration. The variable was never declared

// check againts undeclared variables
typeof value === "undefined"; // works

// check againts declared variables with no value
value === undefined; // ReferenceError: value is not defined

There are also issues with undefined = true being valid. But you don't really care about that. No-one is stupid enough to alter undefined globally these days.

I also know of bugs with instanceof being broken. I can't give you the exact reason why Array.isArray is better though.

You will find criticism on instanceof in the JavaScript Garden

If you read this Article It mentions how instanceof does not work across seperate frames / windows / iframes.

Because instanceof checks againts Array and each window has it's own window.Array.



来源:https://stackoverflow.com/questions/6006156/javascript-testing-variables-for-undefined-value-testing-whether-object-is-arr

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