2

这段 JavaScript 在没有"use strict";. 但是如何检查全局变量是否存在严格模式以及它具有什么类型而不会遇到undeclared variable错误?

if (!(typeof a === 'object')) {
    a = ... /* complex operation */
}
4

3 回答 3

2

我找到了一种有效的方法来检查全局变量是否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 = ...
}
于 2015-08-27T10:33:20.723 回答
1

创建隐式全局变量是严格模式下的错误。您必须明确创建全局:

window.a = ... /* complex operation */

typeof a应该仍然像以前一样工作。

于 2015-07-21T14:44:51.540 回答
0

问题是你有一个未声明的变量......你必须把它放在第一位: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.
}
于 2015-07-21T13:50:32.220 回答