循环由于某种原因被卡住,然后最终返回未定义

这就是我试图解决的问题:给定:一个包含名称哈希的数组


Return:格式为用逗号分隔的名称列表的字符串,但最后两个名称除外,最后两个名称应以 & 符号分隔。


例:


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 ''

注意:所有哈希值都经过预先验证,并且仅包含 A-Z、a-z、“-”和 “。


这是我的代码:


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>

如何修复此问题?


万千封印
浏览 62回答 2
2回答

摇曳的蔷薇

这是因为 forEach 不会返回任何内容,请尝试改用映射函数。var&nbsp;finalNames&nbsp;=&nbsp;names.map(returnNames);

沧海一幻觉

正如他们已经指出的那样,返回 。相反,您可以使用此来修改您的函数Array.prototype.forEachundefined.mapreturnNamesvar finalName;var notFinal;function list(names){&nbsp; // Changed .forEach with .map&nbsp; var finalNames = names.map(returnNames);&nbsp; console.log(typeof finalNames);&nbsp; function returnNames(person) {&nbsp; &nbsp; // If you only need to get the object values, use Object.values instead of Object.keys&nbsp; &nbsp; return Object.values(person);&nbsp; }&nbsp; for(var i = 0; i < finalNames.length; i++) {&nbsp; &nbsp; // Added + 1 because i could never be equal to the array length&nbsp; &nbsp; // Note that you'll need to make 1 or 2 more changes before this code works as expected&nbsp; &nbsp; if (finalNames.length / (i + 1) == 1) {&nbsp; &nbsp; &nbsp; finalName = "& " + finalNames[i];&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; notFinal = finalNames[i] + ", ";&nbsp; &nbsp; }&nbsp; }&nbsp; console.log(notFinal + finalName);}list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript