开发者问题收集

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

2020-06-07
316

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

返回:格式化为名称列表的字符串,除最后两个名称外,其他名称均以逗号分隔,最后两个名称应以 & 符号分隔。

示例:

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>

如何修复它?

3个回答

这是因为 forEach 没有返回任何内容,请尝试使用 map 函数。

var finalNames = names.map(returnNames);
Gustavo A Olmedo
2020-06-07

正如他们已经指出的那样, Array.prototype.forEach 返回 undefined 。相反,您可以使用 .map 来实现这一点,修改您的 returnNames 函数

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'}])
Juan Elfers
2020-06-07

您可以像下面这样简化代码。

function list(names){
  //Determine length of array (= number of names)
  const len = names.length;
  //Use a simple for loop to go through the array
  let newNames = "";
  for (i=0; i<len; i++) {
    newNames += names[i].name;
    if ( i<len-2 ) newNames += ", "
      else if ( i<len-1 ) newNames += " & "
  }
  console.log(newNames);
}

list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
list([{name: 'Bart'}, {name: 'Lisa'}]);
list([{name: 'Bart'}]);
Gerard
2020-06-07