2015-10-18 58 views

回答

2

您可以使用一個簡單的循環for

for (i = 0; i < array.length; i++) 
    document.writeln((i+1) + ": " + array[i]); 

,並使用document.writeln將其打印出來。請參閱下面的工作片段。

片段

array = ["example1", "example2", "example3"]; 
 
for (i = 0; i < array.length; i++) 
 
    document.writeln((i+1) + ": " + array[i]);

注:document.writeln()實現不同的許多倍。所以,你應該使用:

document.getElementById("id_of_div").innerHTML += (i+1) + ": " + array[i]; 
+2

最好不要提示新手使用'document.write'由於意外的行爲和不同的實現... –

+0

@TJ當然好友。讓我更新並澄清問題。 –

+0

@TJ更新了答案。 –

0

嘗試使用for循環:

for (var i=0; i<array.length; i++) 
    console.log(i + ". " + array[i]); 
0

您可以使用標準陣列方法來得到你之後的結果。 MDN在array iteration methods上有一些很棒的文檔。

var examples = ["example1", "example2", "example3"]; 

// You can use reduce to transform the array into result, 
// appending the result of each element to the accumulated result. 
var text = examples.reduce(function (result, item, index) { 
    var item_number = index + 1; 

    return result + " " + item_number + ". " + item; 
}, ""); 

// You can use a variable with forEach to build up the 
// result - similar to a for loop 
var text = ""; 

examples.forEach(function (item, index) { 
    var item_number = index + 1; 

    text = text + " " + item_number + ". " + item; 
}); 

// You can map each element to a new element which 
// contains the text you'd like, then join them 
var text = examples.map(function (item, index) { 
    var item_number = index + 1; 
    return item_number + ". " + item; 
}).join(" "); 

// You can put them into an HTML element using document.getElementById 
document.getElementById("example-text-result").innerHTML = text; 

// or print them to the console (for node, or in your browser) 
// with console.log 
console.log(text); 
相關問題