4 回答
TA贡献1817条经验 获得超6个赞
在返回之前,newArr您可以检查它的长度,如果它为零,则返回“No matches”。
let people = [{
name: "Nick",
studying: "JS",
age: "33"
},
{
name: "Joseph",
studying: "JS",
age: "137"
},
{
name: "Jeff",
studying: "education",
age: "1897374"
}
];
function returnArrOfNames(people, string) {
let newArr = []
for (let i = 0; i < people.length; i++) {
if (people[i].studying === string) {
newArr.push(people[i].name)
}
}
if (newArr.length === 0) {
return "No matches";
}
return newArr
}
console.log(returnArrOfNames(people, "JS"));
TA贡献1824条经验 获得超8个赞
编辑:对不起,我发布了与其他人相同的答案。
您可以只在 for 循环之外添加该 if 语句。像这样:
let people = [
{name : "Nick",
studying : "JS",
age : "33"},
{name : "Joseph",
studying : "JS",
age : "137"},
{name : "Jeff",
studying : "education",
age : "1897374"}
];
function returnArrOfNames(people, string) {
let newArr = []
for (let i = 0; i < people.length; i++) {
if (people[i].studying === string) {
newArr.push(people[i].name)
}
}
if (newArr.length == 0){
return console.log("no matches")
}
console.log(newArr);
return newArr
}
returnArrOfNames(people, "JS")
TA贡献1155条经验 获得超0个赞
更简单的是array.reduce方法,使用三元条件返回
const people =
[ { name: 'Nick', studying: 'JS', age: '33' }
, { name: 'Joseph', studying: 'JS', age: '137' }
, { name: 'Jeff', studying: 'education', age: '1897374' }
]
function returnArrOfNames(arr, study)
{
let newArr = arr.reduce((a,c)=>
{
if (c.studying===study) a.push(c.name)
return a
}, [])
return newArr.length ? newArr : 'no matches'
}
console.log(' JS ? ->', returnArrOfNames(people, "JS") ) // Array [ "Nick", "Joseph" ]
console.log(' xx ? ->', returnArrOfNames(people, "xx") ) // "no matches"
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1863条经验 获得超2个赞
您可以利用Array prototype's map和filter方法来获得结果:
let people = [{
name: "Nick",
studying: "JS",
age: "33"
},
{
name: "Joseph",
studying: "JS",
age: "137"
},
{
name: "Jeff",
studying: "education",
age: "1897374"
}
];
function returnArrOfNames(people = [], studying) {
const NO_MATCHES = 'No Matches'
const isEmpty = people.length === 0
if (isEmpty) {
return NO_MATCHES
}
const filterFn = i => i.studying === studying
const filteredPeople = people.filter(filterFn)
const isEmptyFilteredPeople = filteredPeople.length === 0;
if(isEmptyFilteredPeople) return NO_MATCHES
const mapFn = i => i.name
const mappedPeople = filteredPeople.map(mapFn);
return mappedPeople
}
console.log(returnArrOfNames(people, "JS"));
添加回答
举报