如何使用javascript从数组中打印元素

时间:2015-10-18 13:25:49

标签: javascript arrays

我有数组元素,例如array = [“example1”,“example2”,“example3”]。我不知道如何以这种格式打印:1。example1 2. example2 3.例3 ...任何帮助?

6 个答案:

答案 0 :(得分:4)

您可以使用简单的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];

答案 1 :(得分:1)

您可以使用标准数组方法来获得您想要的结果。 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);

答案 2 :(得分:1)

使用forEach,如下所示

var a = ["a", "b", "c"];
a.forEach(function(entry) {
  console.log(entry);
});

答案 3 :(得分:0)

尝试使用for循环:

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

答案 4 :(得分:0)

您可以尝试以下操作:-

var arr = ['example1', 'example2', 'example3']
for (var i = 0; i < arr.length; i++){
    console.log((i + 1) + '. ' + arr[i])
}

答案 5 :(得分:0)

为此使用forEach,如下所示(ES6)

var a = ["a", "b", "c"];
a.forEach((element) => {
        console.log(element)
    }
);