2 回答

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是因?yàn)?forEach 不會(huì)返回任何內(nèi)容,請(qǐng)嘗試改用映射函數(shù)。
var finalNames = names.map(returnNames);

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
正如他們已經(jīng)指出的那樣,返回 。相反,您可以使用此來(lái)修改您的函數(shù)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'}])
添加回答
舉報(bào)