'return' 没有输出所有结果

'return' is not outputting all results

我有一个简单的函数,我想获取一个大小写混合的字符串数组,并输出数组中首字母大写的每个值。

当我使用 'return' 元素调用我的函数时,控制台日志仅生成数组中的第一个值 -> 'London'。

如何生成每个字符串首字母大写的整个城市数组???

注意:当我将return替换为console.log(result)时,函数调用运行顺利,但在控制台中,数组输出大写字母的结果后,'undefined'值类型对应行'console.log(capFirstLetter(cities));'

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

let capFirstLetter = (list) => {
  for(let i = 0; i < list.length; i++) {
    let input = list[i].toLowerCase();
    let firstLetter = input[0];
    let result = input.replace(firstLetter, firstLetter.toUpperCase());
    return restult;
  }
}

console.log(capFirstLetter(cities));

注意:这是控制台中的内容,我将 return 结果替换为 console.log(result)

London ->script.js:60
Manchester ->script.js:60
Birmingham ->script.js:60
Liverpool->script.js:60
undefined ->script.js:64

script.js.60 与行 console.log(result) & script.js.64 对应行

您应该使用 .map 将一个数组转换为另一个数组 - return .map 回调中的新数组元素:

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

let capFirstLetter = (list) => {
  return list.map((input) => {
    input = input.toLowerCase();
    let firstLetter = input[0];
    return input.replace(firstLetter, firstLetter.toUpperCase());
    console.log(result);
  });
}

console.log(capFirstLetter(cities));

或者,为了更简洁,使用正则表达式和替换函数:

const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

const capFirstLetter = list => list.map(
  (input) => input.replace(
    /(.)(.*)/g,
    (_, firstLetter, rest) => firstLetter.toUpperCase() + rest.toLowerCase()
  )
);
console.log(capFirstLetter(cities));

使用旧式 for 循环,您必须在每次迭代结束时 push 到一个新数组:

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

let capFirstLetter = (list) => {
  const newArr = [];
  for(let i = 0; i < list.length; i++) {
    let input = list[i].toLowerCase();
    let firstLetter = input[0];
    let result = input.replace(firstLetter, firstLetter.toUpperCase());
    newArr.push(result);
  }
  return newArr;
}

console.log(capFirstLetter(cities));

When I call my function, with the 'return' element, the console log only produces the first value in the array -> 'London'.

发生这种情况是因为您的 return 在第一个循环后停止迭代 (for),因此 result 将仅包含第一个城市。

Note: When I replace return with console.log(result), the function call works smoothly, but in the console, directly after the array has outputted the results with capitalized letters, an 'undefined' value type corresponds to the line console.log(capFirstLetter(cities));

发生这种情况是因为您的函数没有 return 任何东西(在 JS 中这意味着该函数将 return 未定义)。

要使其正常工作,您可以使用地图:

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

let capFirstLetter = list => list.map(city => city.charAt(0).toUpperCase() + city.slice(1).toLowerCase());

console.log(capFirstLetter(cities));