2016-04-16 17 views
0

が含まれている次の関数は、配列を入れ子にしているオブジェクトを再帰的にオブジェクトを検索した場合:最初のconsole.log(arr)チェック配列が指定されたオブジェクト

function findDeep(arr, obj) { 
    console.log(arr) 
    if (arr.indexOf(obj) !== -1) { 
    console.log(arr) 
    return arr 
    } else { 
    arr.forEach(item => { 
     if (item.children) findDeep(item.children, obj) 
    }) 
    } 
} 

const colors = { 
    children: [ 
    { 
     name: 'white', 
    }, 
    { 
     name: 'yellow', 
     children: [ 
     { 
      name: 'black' 
     } 
     ] 
    } 
    ] 
} 

const color = { 
    name: 'black' 
} 

findDeep(colors.children, color) 

はマッチした配列ログインん:

[ 
    { name: 'black' } 
] 

をしかし、彼はsecond console.log(arr)に何も記録しません。 arr.indexOf(obj)を返すべきではないので、2番目のconsole.log(arr)は配列をログに記録しますか?

ここにはCodePenがあります。

+0

プロパティの順序が常に同じ場合は、[JSON.stringify](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify )。 – destoryer

答えて

2

(配列でテストし、提示するindexOf渡された)オブジェクトの両方が同じ基準を指していない限りあなたはindexOfを使用してアレイにobjectindexを見つけることができません。例えば

var a = { 
 
    a: 10 
 
}; 
 
var b = [{ 
 
    a: 10 
 
}, { 
 
    b: 20 
 
}]; 
 
console.log(b.indexOf(a)); // Object `a` and Object in `0th` index of the array are having similar `key-values`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

しかし、

var a = { 
 
    a: 10 
 
}; 
 
var b = [a, { 
 
    b: 20 
 
}]; 
 
//`0th` index in the array is nothing but a variable holding `object` 
 
console.log(b.indexOf(a)); //Same variable is tested in `indexOf`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

From the docs,indexOf()は、厳密な等価性(===またはtriple-equals演算子で使用されるのと同じ方法)を使用して、searchElementと配列の要素を比較します。オペランドが同じオブジェクトを参照する場合のオブジェクトを比較発現のみ真である

、ため

{} === {}falseとして評価されます。両方のオペランドがオブジェクトである場合には、JavaScriptはオペランドがメモリ内の同じオブジェクトを参照するとき等しい内部参照を比較します。[Ref]

あり、いくつかのソリューションやアプローチがあるが、それらのすべてが反復をやってvalueを比較しますオブジェクト内のkeyのこれを参照してくださいanswer

+0

ありがとうございます。素晴らしい説明。 – alexchenco

+0

私はそれが助けてうれしい! _Happy Coding mate_ – Rayon

関連する問題