以下是对代码的说明(现在我的代码保持返回未定义): 使用reduce函数迭代单词数组并根据以下条件构造解码语句(字符串): 如果数组元素的长度恰好是三个字符,请在累加器中添加一个空格字符 否则,将数组元素的LAST字符大写并将其添加到累加器
function decode(sentence) {
let words = sentence.split(' ');
let newWords = words.reduce(function(acc,word){
if (word.length < 3) {
acc += ' ';
console.log(acc);
}
else {
acc += (word[word.length-1].toUpperCase());
console.log(acc);
}
}, '');
return newWords;
}
console.log(decode('noggin oreo the moon time tele steed his tent apollo her lives though shoo tofu budapest'));
答案 0 :(得分:3)
您没有在谓词中返回累加器:
let newWords = words.reduce(function(acc, word) {
if (word.length < 3) {
acc += ' ';
console.log(acc);
} else {
acc += word[word.length - 1].toUpperCase();
console.log(acc);
}
return acc;
}, '');
由于您没有返回累加器,因此每次调用谓词时,您都将未定义为下一个谓词调用的累加器。