我有一个包含各种动物的对象:
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}]
我只想返回猫类动物的名称。我正在努力这样做。这是我的尝试:
var cats = []
function onlyCats(array) {
if (toonimals.animal === 'cat') {
cats.push(toonimals.name)
}
return cats
}
console.log(onlyCats(toonimals));
目前,它仅返回空数组,因此 .push()
方法由于某种原因不起作用。
提前谢谢您。
最佳答案
您必须循环数组到 filter()
这个动物。然后使用map()
修改数组以返回名称:
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];
function onlyCats(array) {
return array.filter(a => a.animal === 'cat').map(a => a.name);
}
console.log(onlyCats(toonimals));
在forEach()
的帮助下以您的方式:
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];
var cats = []
function onlyCats(array) {
array.forEach(function(animal){
if (animal.animal === 'cat') {
cats.push(animal.name)
}
});
return cats;
}
console.log(onlyCats(toonimals));
关于javascript - 根据属性返回对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54720292/