JavaScript:确定变量是否为对象文字

时间:2018-09-02 04:49:33

标签: javascript

我正在寻找一种确定给定变量是否是对象文字而不是其他任何东西的方法。在下面的示例中,我只希望a返回true和其他任何给定的对象。

var a = {};
var b = [];
var c = new Set();

console.log('typeof:');
console.log('  Literal: ', typeof a === 'object' );
console.log('  Array: ', typeof b === 'object' );
console.log('  Array: ', typeof b === 'object' && !b.prototype );
console.log('  Array: ', typeof b === 'object' && b instanceof Object );
console.log('  Array: ', typeof b === 'object' && !b instanceof Array );
console.log('  Set: ', typeof c === 'object' );
console.log('  Set: ', typeof c === 'object' && !c.prototype );
console.log('  Set: ', typeof c === 'object' && c instanceof Object );
console.log('  Set: ', typeof c === 'object' && !c instanceof Set );

instanceof似乎可以通过硬编码类进行检查,但这对于我想做的事情不可行。

3 个答案:

答案 0 :(得分:1)

一种选择是获取原型构造函数的name

var a = {};
var b = [];
var c = new Set();

const type = obj => Object.getPrototypeOf(obj).constructor.name;
console.log(type(a));
console.log(type(b));
console.log(type(c));

const isPlainObject = obj => Object.getPrototypeOf(obj).constructor.name === 'Object';
console.log(isPlainObject(a));
console.log(isPlainObject(b));
console.log(isPlainObject(c));

答案 1 :(得分:1)

您可以使用constructor检查对象的Object属性:

var a = {};
var b = [];
var c = new Set();

console.log('a:', a.constructor === Object);
console.log('b:', b.constructor === Object);
console.log('c:', c.constructor === Object);

答案 2 :(得分:0)

我认为像Object.isLiteral()这样的函数应该是本机的

var a = {};
var b = [];
var c = new Set();

Object.prototype.isLiteral = function() {
  return this.constructor === Object || false;
};

const value = a.isLiteral();
console.log(value);