使用JavaScript从上一个循环中获取价值

时间:2016-12-30 20:55:19

标签: javascript html

我需要保持来自authorId = 1的循环的值,然后在下一个循环中将其打印为另一个值(authorId = 3)。我的意思是我需要保留authorSurname.value(id = 1)并将其作为secondAuthor.value在循环(authorId = 3)中打印,因为在循环(authorId = 3)中,字符串authorSurname采用另一个值。你能告诉我怎么解决它?

  if(authorId === 0) { 

div.innerHTML = firstAuthorSurname.value + year.value + page.value + pageOtherValue;
}

else if (authorId === 1) {
       div.innerHTML = firstAuthorSurname.value + " i " + authorSurname.value + " (" + year.value + "); 
       var secondAuthorSurname = authorSurname.value;
}

else if (authorId === 2) {
    return secondAuthorSurname; 
    div.innerHTML = firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + " (" + year.value + ") " + firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + ", " + year.value + ")" + firstAuthorSurname.value + ", " + secondAuthorSurname.value + " and " + authorSurname.value + ", " + year.value + ") showed that... ";
}

1 个答案:

答案 0 :(得分:0)

您的代码不包含循环,但如果您想保存一个值以在for循环之外使用,请在循环外声明变量,然后您将在循环外访问它。

text = "";
cars = ["honda", "chevy"];
for (i = 0; i < cars.length; i++) { 
  text += cars[i]; 
}
console.log(text);
>>hondachevy

如果您尝试在for循环中的if语句中保存要在不同条件中使用的值,则可以遵循相同的模式

text = "";

for (i = 0; i < 4; i++) { 
  if(i === 0){
   text += "to be used when i is 1";
 }
 else if(i === 1){
   console.log(text);
   text += " hello";
 }
}
console.log(text);

输出

>>to be used when i is 1
>>to be used when i is 1  hello

另外,为什么不使用switch语句而不是long if if else。请参阅以下链接,了解如何在javascript中执行switch语句。

http://www.w3schools.com/js/js_switch.asp