<js>需要一个使用while循环添加“!!!”的函数到数组

时间:2017-03-07 20:22:52

标签: javascript arrays

尝试搜索此失败。我需要使用while循环来添加“!!!”到字符串数组中每个元素的末尾。我尝试了几种不同的方法,最新的方法是:

var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout",
"He hated the sound of his own voice"];

function johnLennonFacts(facts) {
var newFacts=[];
var i = 0;
while (i < 4) {

newFacts[i] = facts[i] +="!!!";
i++;
}
return newFacts;
}

必须是所有js没有我知道的库。我是新手代码(显然)。我知道有更好的方法可以做到这一点,但我必须使用while循环。提前谢谢。

4 个答案:

答案 0 :(得分:0)

var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout",
"He hated the sound of his own voice"];

function johnLennonFacts(facts) {
    var newFacts=[];
    var i = 0;
    while (i < facts.length) {
        newFacts[i] = facts[i] + "!!!";
        i++;
    }
    return newFacts;
}

console.log(johnLennonFacts(facts));

答案 1 :(得分:0)

试试这个:

var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout",
"He hated the sound of his own voice"];

function johnLennonFacts(facts) {
var newFacts=[];
var i = 0;
while (i < 4) {

newFacts[i] = facts[i] +"!!!";
i++;
}
return newFacts;
}

您不需要在字符串中添加=,因为您已经在设置字符串。顺便说一下,+=是一个赋值运算符。另外,不要忘记在代码中调用您的函数。

答案 2 :(得分:0)

如果你所要做的就是追加“!!!”对于数组项 - 您可以在不创建新数组的情况下执行此操作 - 只需更改现有数组即可。以下控制台记录更改的数组。还要记住,它还不足以具备该功能 - 为了使其工作 - 您还需要调用它。我也改变了它将数组的长度作为上限 - 而不是硬编码ti为4 - 这更好,因为如果你改变数组的内容 - 你不想担心改变硬编码值。

此外,“+ =”运算符是说明以下内容的简便方法:...
事实[i] =事实[i] +“!!!” ...;在这种情况下,因为我们正在改变初始数组的值。

//sets the array
var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout",
"He hated the sound of his own voice"];

//alters the array when called
function johnLennonFacts(facts) {
  var i = 0;
    while (i < facts.length) {
       facts[i] += "!!!";
     i++;
    }
    console.log(facts);
  }
  
 //calls the function to alter the array
 johnLennonFacts(facts)

答案 3 :(得分:-1)

这很有用。我没有必要调用或者调用console.log,因为我正在运行的JS是在IDE中(对于一门课程)关于+ =的澄清确实有帮助。感谢所有帮助,非常感谢。

//sets the array
var facts = ["He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout",
"He hated the sound of his own voice"];

//alters the array when called
function johnLennonFacts(facts) {
  var i = 0;
    while (i < facts.length) {
       facts[i] += "!!!";
     i++;
    }
    console.log(facts);
  }
  
 //calls the function to alter the array
 johnLennonFacts(facts)