我有一个包含元素的数组,例如array = ["example1", "example2", "example3"]。
我该如何以以下格式打印它?
- example1 2. example2 3. example 3...
我有一个包含元素的数组,例如array = ["example1", "example2", "example3"]。
我该如何以以下格式打印它?
可以像下面这样使用forEach
来实现:
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
您可以使用简单的 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];
document.write
,因为它的行为不可预测且实现方式不同。 - T J可以使用forEach进行遍历(ES6语法):
var a = ["a", "b", "c"];
a.forEach((element) => {
console.log(element)
}
);
for (var i=0; i<array.length; i++)
console.log(i + ". " + array[i]);
您可以使用标准数组方法来获得您想要的结果。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);
var arr = ['example1', 'example2', 'example3']
for (var i = 0; i < arr.length; i++){
console.log((i + 1) + '. ' + arr[i])
}
let exampleArray = ["example1", "example2", "example3"];
let result = [];
for (let i = 0; i < exampleArray.length; i++) {
result += i + 1 + ". " + exampleArray[i] + " ";
}
console.log(result);
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);
我正在解决这样一个问题,然后我做了这个。
const multiLanguages = ["C is fun", "Python is cool", "JavaScript is amazing"];
for (let i = 0; i < multiLanguages.length; i++) {
console.log(multiLanguages[i]);
}