Javascript 如何使用javascript打印数组中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33198429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print elements from array with javascript
提问by Komi Dumity
I have array with elements for example array = ["example1", "example2", "example3"]. I don't know how to print in this format: 1. example1 2. example2 3. example 3...Any help?
我有包含元素的数组,例如 array = ["example1", "example2", "example3"]。我不知道如何以这种格式打印: 1. example1 2. example2 3. example 3 ...有帮助吗?
回答by Praveen Kumar Purushothaman
You can use a simple for
loop:
您可以使用一个简单的for
循环:
for (i = 0; i < array.length; i++)
document.writeln((i+1) + ": " + array[i]);
And use the document.writeln
to print it out. See the below working snippet.
并使用 将document.writeln
其打印出来。请参阅下面的工作片段。
Snippet
片段
array = ["example1", "example2", "example3"];
for (i = 0; i < array.length; i++)
document.writeln((i+1) + ": " + array[i]);
Note:The
document.writeln()
is implemented differently many times. So you should use:document.getElementById("id_of_div").innerHTML += (i+1) + ": " + array[i];
注:该
document.writeln()
实施不同的许多倍。所以你应该使用:document.getElementById("id_of_div").innerHTML += (i+1) + ": " + array[i];
回答by Vivek Kasture
Use forEach
for this like below
forEach
像下面这样使用
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
回答by iblamefish
You can use standard array methods to get the result you're after. MDN has some great documentation on array iteration methods.
您可以使用标准数组方法来获得您想要的结果。MDN 有一些关于数组迭代方法的很棒的文档。
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);
回答by Komi Dumity
Try to use for loop :
尝试使用 for 循环:
for (var i=0; i<array.length; i++)
console.log(i + ". " + array[i]);