gpt4 book ai didi

javascript - 基于属性返回对象值

转载 作者:行者123 更新时间:2023-11-29 18:44:41 25 4
gpt4 key购买 nike

我有一个包含各种动物的对象:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com