这是我要解决的问题:Given: an array contains hashes of names
返回: 格式为以逗号分隔的名称列表的字符串,最后两个名称除外,最后两个名称应由 & 号分隔。
例子:
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
注意:所有哈希都经过预先验证,并且仅包含 AZ、az、'-' 和 '。
这是我的代码:
var finalName;
var notFinal;
function list(names){
var finalNames = names.forEach(returnNames);
console.log(typeof finalNames);
function returnNames() {
for (var i = 0; i<names.length; i++) {
var nameValue = Object.keys(names[i]).map(key => names[i][key])
}
}
for(var i = 0; i<finalNames.length; i++) {
if (finalNames.length / i == 1) {
finalName = "& " + finalNames[i];
}
else {
notFinal = finalNames[i] + ", ";
}
}
console.log(notFinal + finalName);
}
list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
它卡在循环中,最后报错:
TypeError: Cannot read property 'length' of undefined
at list
at /home/codewarrior/index.js:30:1
at Object.handleError
<anonymous>
我如何解决它?