2つの配列が同一かどうかを調べる関数を作成していますが、現在(配列内にある可能性がある)という2つのオブジェクトが同じかどうかを確認することに固執しています。は同じです。内部for..inループ
私のコードを少し説明するために、私は、関数が終わった時に返されると、それは二番目の配列またはに存在する最初の配列の各要素に対してtrue
のいずれかが含まれている必要がありeq
という名前の変数を持っていますundefined
要素がない場合。
また、再帰IIFEを使用して、オブジェクトにサブオブジェクトがあり、サブオブジェクトも同じかどうかを確認します。配列要素がオブジェクトリテラルであるかどうかを確認するために、私はel.constructor === Object
を使用します。
100%確実ではないが、for..in
ループ内で何か間違ったことをしていると思います。
コード:
function equals(a, b) {
return (a === b && a !== null) || (a.length === b.length && (function(a, b) {
var eq = [];
a.forEach(function(el1, index) {
b.forEach(function(el2) {
if (el1 === el2) eq[index] = true;
else if (el1.constructor === el2.constructor && el1.constructor === Object) {
/* a -> the object of the first array
* b -> the object of the second array
* c -> eq[index] then eq[index][i] provided how deep it goes */
(function rec(a, b, c) {
c = [];
var i = 0;
for (var prop in a) {
for (var attr in b) {
if (prop === attr && a[prop] === b[attr]) c[i] = true;
else if (prop === attr && a[prop].constructor === b[attr].constructor
&& a[prop].constructor === Object) {
rec(a[prop], b[attr], eq[index][i]);
}
}
i++;
}
})(el1, el2, eq[index]);
}
});
});
return /*!~eq.indexOf(undefined);*/ eq;
})(a, b));
}
/* Use */
var a = [1, {a: "a", b: "b" }, 4, 6],
b = [{a: "a", b: "b"}, 1, 7, 6];
equals(a, b);
例1:(単純な配列のために正常に動作)
var
a = [1, 3, 4, 6],
b = [3, 1, 7, 6];
equals(a, b); // returns: [true, true, undefined, true]
例2:(オブジェクトに対して動作しない)
var
a = [1, {a: "a", b: "b"}, 4, 6],
b = [{a: "a", b: "b"}, 1, 7, 6];
equals(a, b); /* returns: [true, undefined, undefined, true]
SHOULD return: [true, [true, true], undefined, true] */
任意の助けを大幅に高く評価されるだろう。
私はすでに二つの配列を比較する関数が多数のライブラリやフレームワークの1つに存在するかなり確信しています。なぜホイールを再発明するのですか? –
私の大学@HubertGrzeskowiakのための練習です:) –
ああ。そして、要素の順序を無視して配列を比較したいのですか? –