JavaScript:测试基元的相等性

Agi*_*ble 0 javascript comparison

假设我有两个对象只有基元作为成员的属性(例如,对象没有函数或对象成员):

var foo = {
    start: 9,
    end: 11
};

var bar = {
    start: 9, 
    end: 11
};
Run Code Online (Sandbox Code Playgroud)

鉴于这样的两个对象,我想知道他们的所有成员是否具有相同的值.

现在我正在做:

if (foo.start === bar.start && foo.end == bar.end) {
    // same member values
}
Run Code Online (Sandbox Code Playgroud)

但是我将不得不处理可能有几十个原始成员的对象.

是否有内置于JavaScript中的内容可以让我轻松比较它们?比较所有价值观的最简单方法是什么?

T.J*_*der 6

如果两个对象都是Objects(例如,通过文字符号[ {}] 创建,或者new Object不是[说] new Date),则可以这样做:

function primativelyEqual(a, b) {
    var name;
    for (name in a) {
        if (!b.hasOwnProperty(name) || b[name] !== a[name]) {
            // `b` doesn't have it or it's not the same
            return false;
        }
    }
    for (name in b) {
        if (!a.hasOwnProperty(name)) {
            // `a` doesn't have it
            return false;
        }
    }

    // All properties in both objects are present in the other,
    // and have the same value down to the type
    return true;
}
Run Code Online (Sandbox Code Playgroud)

for..in迭代对象属性的名称.hasOwnProperty告诉你实例本身(而不是其原型链的成员)是否具有该属性.!==检查两个值之间的任何不等式,而不进行任何类型强制.通过循环遍历两个对象的属性名称,您知道它们具有相同数量的条目.

如果实现具有Object.keysECMAScript5 的新功能,您可以将其快捷一点:

function primativelyEqual(a, b) {
    var name, checkedKeys;

    checkedKeys = typeof Object.keys === "function";
    if (checkedKeys && Object.keys(a).length !== Object.keys(b).length) {
        // They don't have the same number of properties
        return false;
    }
    for (name in a) {
        if (!b.hasOwnProperty(name) || b[name] !== a[name]) {
            // `b` doesn't have it or it's not the same
            return false;
        }
    }
    if (!checkedKeys) {
        // Couldn't check for equal numbers of keys before
        for (name in b) {
            if (!a.hasOwnProperty(name)) {
                // `a` doesn't have it
                return false;
            }
        }
    }

    // All properties in both objects are present in the other,
    // and have the same value down to the type
    return true;
}
Run Code Online (Sandbox Code Playgroud)

实例

但是上面的两个版本都假设对象没有从它们的原型继承任何可枚举的属性(因此我的开头声明是关于它们的Objects).(我也假设没有人添加任何东西Object.prototype,这是人们很快就学不到的疯狂事情.)

绝对有可能进一步改进以概括它,甚至使它通过相同的定义下降到对象属性,但是在你描述的范围内(并且在大多数合理的部署的范围内),这应该没问题.