为什么这个循环使用函数参数只返回一次?

Why is this loop using function parameter returning only once?

const alphabets= {
  first: ["a", "b", "c"],
  second: ["d", "e", "f"],
  third: ["g", "h"]
};    

function trial(arr) {

  for (let i = 0; i < arr.length; i++) {
    const argh = `<li class = "text-warning">${i}<li>`;
    return argh;
  }
};

console.log(trial(alphabets.second));

我在用数字替换条件的函数外尝试了相同的 'for loop',它工作正常。为什么放入函数,条件中使用参数,只循环一次?

因为return语句会停止你的函数。也许您想在 return 之前连接一个字符串?

function trial(arr) {

  let returnValue = '';

  for (let letter of arr) {
    returnValue += `<li class = "text-warning">${letter}<li>`;
  }

  return returnValue;
};

如果你想要一个数组,你可以推送到一个数组,然后在循环完成后 return。

function trial(arr) {
  const argh = [];
  for (let i = 0; i < arr.length; i++) {
    argh.push(`<li class = "text-warning">${i}<li>`);
  }
  return argh;
};

return

The return statement ends function execution and specifies a value to be returned to the function caller.

您可以在 for 循环外声明变量,并在每次迭代中连接 htmlString 并在循环完成后 return 变量。

const alphabets= {
  first: ["a", "b", "c"],
  second: ["d", "e", "f"],
  third: ["g", "h"]
};    

function trial(arr) {
  let argh='';
  for (let i = 0; i < arr.length; i++) {
    argh += `<li class = "text-warning">${i}<li>`;
  }
  return argh;
};

console.log(trial(alphabets.second));