2 回答
TA贡献1824条经验 获得超5个赞
正如他们已经指出的那样,返回 。相反,您可以使用此来修改您的函数Array.prototype.forEachundefined.mapreturnNames
var finalName;
var notFinal;
function list(names){
// Changed .forEach with .map
var finalNames = names.map(returnNames);
console.log(typeof finalNames);
function returnNames(person) {
// If you only need to get the object values, use Object.values instead of Object.keys
return Object.values(person);
}
for(var i = 0; i < finalNames.length; i++) {
// Added + 1 because i could never be equal to the array length
// Note that you'll need to make 1 or 2 more changes before this code works as expected
if (finalNames.length / (i + 1) == 1) {
finalName = "& " + finalNames[i];
}
else {
notFinal = finalNames[i] + ", ";
}
}
console.log(notFinal + finalName);
}
list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
添加回答
举报