检查对象在javascript中是否具有一组属性

Ben*_*Ben 6 javascript jquery properties object operators

假设我有一个名为的对象a,我怎么能用a速记来检查它是否有一个特定的多个属性列表,我认为它可以逻辑运算符中使用,

像这样的东西:

var a = {prop1:{},prop2:{},prop3:{}};
if ({1:"prop1",2:"prop2",3:"prop3"} in a)
    console.log("a has these properties:'prop1, prop2 and prop3'");
Run Code Online (Sandbox Code Playgroud)

编辑

如果普通的javascript无法帮助,jQuery会做,但我更喜欢javascript

EDIT2

便携性是特权

p.s*_*w.g 17

最简单的方法是使用传统的&&:

if ("prop1" in a && "prop2" in a && "prop3" in a) 
    console.log("a has these properties:'prop1, prop2 and prop3'");
Run Code Online (Sandbox Code Playgroud)

这不是一个"速记",但它并不比你提出的那么长.

您还可以将要测试的属性名称放在数组中并使用以下every方法:

var propertiesToTest = ["prop1", "prop2", "prop3"];
if (propertiesToTest.every(function(x) { return x in a; })) 
    console.log("a has these properties:'prop1, prop2 and prop3'");
Run Code Online (Sandbox Code Playgroud)

但请注意,这是在ECMAScript 5中引入的,因此在某些旧版浏览器中不可用.如果这是一个问题,您可以提供自己的版本.以下是MDN的实现:

if (!Array.prototype.every) {
  Array.prototype.every = function(fun /*, thisp */) {
    'use strict';
    var t, len, i, thisp;

    if (this == null) {
      throw new TypeError();
    }

    t = Object(this);
    len = t.length >>> 0;
    if (typeof fun !== 'function') {
        throw new TypeError();
    }

    thisp = arguments[1];
    for (i = 0; i < len; i++) {
      if (i in t && !fun.call(thisp, t[i], i, t)) {
        return false;
      }
    }

    return true;
  };
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*pty 7

这是underscore.js库真正闪耀的地方.例如,它提供了一个已填充多边形的every()方法,如对pswg的回答所述:http://underscorejs.org/#every

但是有不止一种方法可以做到这一点; 以下,虽然更详细,也可能适合您的需求,并让您了解更多下划线可以做什么(例如_.keys和_.intersection)

var a = {prop1:{},prop2:{},prop3:{}};
var requiredProps = ['prop1', 'prop2', 'prop3'];
var inBoth = _.intersection(_.keys(a), requiredProps);
if (inBoth.length === requiredProps.length) {
    //code
}
Run Code Online (Sandbox Code Playgroud)


sac*_*024 5

像这样使用Array.reduce

var testProps = ['prop1', 'prop2', 'prop3'];
var a = {prop1:{},prop2:{},prop3:{}};

var result = testProps.reduce(function(i,j) { return i && j in a }, true);
console.log(result);
Run Code Online (Sandbox Code Playgroud)