首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用javascript打印数组中的元素

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

Stack Overflow用户
提问于 2015-10-18 21:25:49
回答 5查看 100.2K关注 0票数 6

我有一个包含数组元素的数组,例如array = "example1","example2","example3“。我不知道如何以这种格式打印: 1. example1 2. example2 3. example 3...Any help?

EN

回答 5

Stack Overflow用户

发布于 2019-01-11 02:37:46

如下所示,请使用forEach

代码语言:javascript
复制
var a = ["a", "b", "c"];
a.forEach(function(entry) {
  console.log(entry);
});

票数 11
EN

Stack Overflow用户

发布于 2016-09-16 22:53:51

你可以使用标准的数组方法来得到你想要的结果。MDN有一些关于array iteration methods的很好的文档。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2020-11-01 07:04:21

使用如下所示的forEach (ES6)

代码语言:javascript
复制
var a = ["a", "b", "c"];
a.forEach((element) => {
        console.log(element)
    }
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33198429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档