在javascript中给出以下2个对象:
myFruit = {
'apple': 14,
'orange': 3,
'pear': 10
}
theirFruit = {
'banana': 10,
'grape': 30,
'apple': 2
}
Run Code Online (Sandbox Code Playgroud)
返回匹配元素数组的最有效方式是什么?每个键的值无关紧要。
下面是一个示例,但有一些事情告诉我,可能有更好的方法。
let matches = [];
let myKey;
Object.keys(myFruit).forEach((key, index) => {
myKey = key;
Object.keys(theirFruit).forEach((theirKey, index) => {
if(myKey === theirKey) {
matches.push(theirKey);
}
});
});
console.log(matches);
// will print: ['apple']
console.log(matches.length);
// will print: 1
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案。
const matches = Object.keys(myFruit).filter(key => key in theirFruit);
console.log(matches); // will output ['apple']Run Code Online (Sandbox Code Playgroud)