这段 JavaScript 没有使用 "use strict";
也能正常运行。但是在严格模式下,如何检查全局变量是否存在以及它的类型,而不会遇到 未声明变量
错误?
if (!(typeof a === 'object')) {
a = ... /* complex operation */
}
这段 JavaScript 没有使用 "use strict";
也能正常运行。但是在严格模式下,如何检查全局变量是否存在以及它的类型,而不会遇到 未声明变量
错误?
if (!(typeof a === 'object')) {
a = ... /* complex operation */
}
我找到了一种有效的方法来检查JavaScript全局变量a
是否存在,而不会触发警告。
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 = ...
}
if(typeof(a) !== 'undefined') ...
。 - Lawrence Dolwindow.a = ... /* complex operation */
typeof a
应该仍然像以前一样工作。
typeof a
should still work as before"*,我的意思是在“非严格”模式下。如果没有表达清楚,我很抱歉。 - Felix Klingvar 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.
}
var a;
。 - user3117575
a
。如果你想让它像全局变量一样运行,可能要在最外层作用域中定义。 - user3117575