这段 JavaScript 在没有"use strict";
. 但是如何检查全局变量是否存在严格模式以及它具有什么类型而不会遇到undeclared variable
错误?
if (!(typeof a === 'object')) {
a = ... /* complex operation */
}
这段 JavaScript 在没有"use strict";
. 但是如何检查全局变量是否存在严格模式以及它具有什么类型而不会遇到undeclared variable
错误?
if (!(typeof a === 'object')) {
a = ... /* complex operation */
}
我找到了一种有效的方法来检查全局变量是否a
存在而不会在 JavaScript 中触发警告。
该
hasOwnProperty()
方法返回一个布尔值,指示对象是否具有指定的属性。
hasOwnProperty()
当请求的变量名在全局空间中不存在时不会触发警告!
'use strict';
if (!window.hasOwnProperty('a')) {
window.a = ...
// Or
a = ...
}
确保a
是一个对象使用
'use strict';
if (!(window.hasOwnProperty('a') && typeof a === 'object')) {
window.a = ...
// Or
a = ...
}
创建隐式全局变量是严格模式下的错误。您必须明确创建全局:
window.a = ... /* complex operation */
typeof a
应该仍然像以前一样工作。
问题是你有一个未声明的变量......你必须把它放在第一位:var a = {};
。但是,这就是我检查这些事情的方法。
var utils = {
//Check types
isArray: function(x) {
return Object.prototype.toString.call(x) == "[object Array]";
},
isObject: function(x) {
return Object.prototype.toString.call(x) == "[object Object]";
},
isString: function(x) {
return Object.prototype.toString.call(x) == "[object String]";
},
isNumber: function(x) {
return Object.prototype.toString.call(x) == "[object Number]";
},
isFunction: function(x) {
return Object.prototype.toString.call(x) == "[object Function]";
}
}
var a = ""; // Define first, this is your real problem.
if(!utils.isObject(a)) {
// something here.
}