如何使用JavaScript打印数组中的元素

16

我有一个包含元素的数组,例如array = ["example1", "example2", "example3"]。

我该如何以以下格式打印它?

  1. example1 2. example2 3. example 3...
10个回答

21

可以像下面这样使用forEach来实现:

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


1
这怎么能接近回答问题呢?运行时,它会在不同的行上打印"a"、"b"和"c"。例如,这怎么打印出项目编号呢?你能解释一下你的答案吗?请通过编辑(更改)您的答案来回复,而不是在评论中回复(不要包含“Edit:”、“Update:”或类似的内容——答案应该看起来像今天写的)。 - Peter Mortensen

15

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

Note: The document.writeln() is implemented differently many times. So you should use:

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

2
不建议新手使用document.write,因为它的行为不可预测且实现方式不同。 - T J
@TJ 当然,伙计。让我更新并澄清问题。 - Praveen Kumar Purushothaman
@TJ 更新了答案。 - Praveen Kumar Purushothaman

6

可以使用forEach进行遍历(ES6语法):

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

1
就像Vivek Kasture的答案一样,这并没有解答问题。 - Peter Mortensen

4

不要在循环中打印,我建议使用一个简单的函数转换来生成一个字符串,然后再进行打印(或以其他方式使用):

var example = ["example1", "example2", "example3"]
var O = example.map( (e, i) => (i + 1 + "." + e) ).join(' ');
console.log(O);

它通过在数组上应用.map(),使用箭头函数将每个数组元素e及其索引i组合成字符串。然后,您只需要使用任何分隔符(例如' ').join()结果数组的元素即可。


1
是的,对于像这样简单的情况,不需要使用显式循环。 - Peter Mortensen
它会扩展吗?还是其中隐藏着Shlemiel the painter’s algorithm(使用短字符串构建长字符串,并为每次添加重新分配和复制)?这不是一个修辞问题。 - Peter Mortensen
@PeterMortensen 感谢您的编辑 - 为什么它不能扩展:https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/ - Christophe

2
尝试使用一个for循环:
for (var i=0; i<array.length; i++)
    console.log(i + ". " + array[i]);

在多个字符串中输出。 - Mykola Tetiuk

2

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

1
你可以尝试这个:-
var arr = ['example1', 'example2', 'example3']
for (var i = 0; i < arr.length; i++){
    console.log((i + 1) + '. ' + arr[i])
}

1
你可以采取以下方法将其打印在一行中:
let exampleArray = ["example1", "example2", "example3"];
let result = [];

 for (let i = 0; i < exampleArray.length; i++) {    
   result += i + 1 + ". " + exampleArray[i] + " ";
 }
 console.log(result);

0
如果你想在ES6中实现这个,reduce将是比map更好的选择。它为你声明了预定义变量,甚至不需要使用join()函数。

var array = ["example1", "example2", "example3"];
var op= array.reduce((ac,cur,ind)=> ac +` ${ind+1}.` + cur,'');
console.log(op);

With Map() and Join()

var array = ["example1", "example2", "example3"];
var op= array.map((e, i) =>`${i+1}.${e}`).join(' ');
console.log(op);


0

我正在解决这样一个问题,然后我做了这个。

const multiLanguages = ["C is fun", "Python is cool",  "JavaScript is amazing"];
for (let i = 0; i < multiLanguages.length; i++) {
  console.log(multiLanguages[i]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接