我有一个包含数组元素的数组,例如array = "example1","example2","example3“。我不知道如何以这种格式打印: 1. example1 2. example2 3. example 3...Any help?
发布于 2019-01-11 02:37:46
如下所示,请使用forEach
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
发布于 2016-09-16 22:53:51
你可以使用标准的数组方法来得到你想要的结果。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);
发布于 2020-11-01 07:04:21
使用如下所示的forEach (ES6)
var a = ["a", "b", "c"];
a.forEach((element) => {
console.log(element)
}
);
https://stackoverflow.com/questions/33198429
复制相似问题