2016-12-30 37 views
-3

我需要保留authorId = 1的循環中的值,然後在下一個循環(authorId = 3)中將其作爲另一個值打印出來。我的意思是我需要保留authorSurname.value(id = 1)並將其作爲secondAuthor.value作爲循環(authorId = 3)打印出來,因爲在循環(authorId = 3)中,字符串authorSurname需要另一個值。你能告訴我如何解決它?使用JavaScript從前一個循環獲得價值

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... "; 
} 
+4

您的示例代碼不包含循環 – rekire

回答

0

您的代碼不包含循環,但如果你想保存到的室外使用for循環聲明外循環變量的值,那麼你將有外循環訪問它。

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

如果你要保存的值在不同的條件下使用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 else。請參閱下面的鏈接以瞭解如何在JavaScript中執行switch語句。

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