2017-08-05 24 views
0

我認爲這個功能是很容易的元素,但我沒能找到解決這個問題的方法:得到輸出1下令,2,3以下使用循環數組

我有一個數組像這樣:

var results = ""; 
var example = ['Bank 1', 'Bank 2', 'Bank 3']; 

我需要使用一個for循環打印每個元素是這樣的:

1 - Bank 1 
2 - Bank 2 
3 - Bank 3 

我雖然使用一個for循環:

for (var i = 0; i < example.length; i++) { 
    results += "<strong>" + i + "</strong>" + " - " + "<strong>" example[i].toUpperCase() + "</strong>\n\n"; 
} 

但結果是:

0 - Bank 1 
1 - Bank 2 
2 - Bank 3 

我想輸出從1開始,但打印相同的方式排列的所有元素:

1 - Bank 1 
2 - Bank 2 
3 - Bank 3 

我怎樣才能做到這一點?

回答

0

變化

results += "<strong>" + i + "</strong>" + " - " + "<strong>" example[i].toUpperCase() + "</strong>\n\n"; 

results += "<strong>" + (i+1) + "</strong>" + " - " + "<strong>" example[i].toUpperCase() + "</strong>\n\n"; 
+0

簡單容易,謝謝你skr。 – zagk

0

試試這個:

for (var i = 0; i < example.length; i++) { 
    results += "<strong>" + (i + 1) + "</strong>" + " - " + "<strong>" + example[i].toUpperCase() + "</strong>\n\n"; 
} 

不要忘記失蹤 「+」 例如前[I] .toUpperCase()

+0

哦,當然。我忘了。謝謝。 – zagk

0

問題出在for循環:

for (var i = 0; i < example.length; i++) { 
    results += "<strong>" + i + "</strong>" + " - " + "<strong>" 
    example[i].toUpperCase() + "</strong>\n\n"; 
} 

i從0開始i++意味着i將得到增加,但每次循環迭代後只會得到增加。所以,當你打印銀行1,i爲0。然後,當你打印銀行2,i是1

要解決它,你需要打印的i+1值:

results += "<strong>" + (i+1) + "</strong>" + " - " + "<strong>" + example[i].toUpperCase() + "</strong>\n\n";