具有如下对象:
var animals = { "dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]};
我想找回具有某种颜色的动物的名字,例如对于"red"
,我想返回一个包含["dog", "cat"]
的数组;
试图做到这一点,但我只能找回Array(0)或Array(1)
function findColor(animals, color) {
var result = [];
if (Object.values(animals).indexOf(color) > -1) {
result.push(color);
}
return result;
}
console.log(findColor(animals, "red"));
答案 0 :(得分:3)
您可以简单地使用Object.keys
和filter
var animals = {
"dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]
};
function findColor(animals, color) {
return Object.keys(animals).filter(key=>animals[key].includes(color))
}
console.log(findColor(animals, 'red'));
为什么我的代码不起作用?
indexOf使用严格的比较,Object.values(animals)返回2d数组,并且您尝试将其与字符串值匹配,您需要执行的操作是遍历键并在2d数组的子数组上使用indexOf >
var animals = {"dog": ["black", "red", "green"],"cat": ["pink", "red", "white"],"bird": ["green", "grey", "yellow"]};
function findColor(animals, color) {
var result = [];
Object.keys(animals).forEach(v => {
if (animals[v].indexOf(color) > -1) {
result.push(v)
}
})
return result;
}
console.log(findColor(animals, "red"));
答案 1 :(得分:1)
您可以使用Object.keys
然后对数组进行迭代,然后根据条件进行检查:
var animals = { "dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]};
function findColor(animals, color) {
let result = []
Object.keys(animals).forEach(key=>{
if(animals[key].indexOf(color)>-1){
result.push(key)
}
});
return result;
}
console.log(findColor(animals, "red"));