如何使用for循环将字符串添加到每个数组元素的末尾?

时间:2018-06-04 22:40:40

标签: javascript arrays for-loop

我要完成下面的功能。我将使用for循环遍历arr参数并添加字符串" Duck"到每个元素的末尾(i.e. arr[0] = "yellow"; should become "yellowDuck".

以下是我给出的内容:

function addDucks(arr, ind) {

  //WRITE YOUR FOR-LOOP HERE
  //For your iterator, declare it with the let keyword, and name it "i"


  //DO NOT TOUCH THIS
  return [arr, ind]
} 

以下是我正在尝试的代码:

function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
    return arr[i] + 'Duck';
  }
  return [arr, ind]
}

1 个答案:

答案 0 :(得分:1)

您的代码很接近,您只是没有将数组中的引用更改为添加了Duck的字符串。将return arr[i] + 'Duck'修改为arr[i] += 'Duck',与arr[i] = arr[i] + 'Duck'

相同

&#13;
&#13;
function addDucks(arr, ind) {
  for (let i = 0; i < arr.length; i++) {
      arr[i] += 'Duck';
  }
  return arr;
}
let ducks = addDucks(['green','purple'], 2);
console.log(ducks);
&#13;
&#13;
&#13;