为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

万千封印 2022-09-23 09:42:06
这就是我试图解决的问题:给定:一个包含名称哈希的数组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>如何修复此问题?
查看完整描述

2 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

这是因为 forEach 不会返回任何内容,请尝试改用映射函数。

var finalNames = names.map(returnNames);


查看完整回答
反对 回复 2022-09-23
?
沧海一幻觉

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'}])


查看完整回答
反对 回复 2022-09-23
  • 2 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信