JS中如何使用alert()显示数组元素?
How to use alert() to show elements of array in JS?
我想尝试打印数组元素(动物),以便它的每个元素都在新行 (\n) 中。不幸的是,我做不到。有人可以使用我在 console.log() 中创建的逻辑来解决该问题吗?是的,我希望单个警报显示给定消息:)
let animals = ["fox", "elephant", "wolf"];
console.log("List of animals:");
for (let animal of animals) {
let itemNum = animals.indexOf(animal) + 1;
console.log(`${itemNum}: ${animal}`);
}
输出:
List of animals:
1: fox
2: elephant
3: wolf
有人能想出同样适用于 alert() 的解决方案吗?
也许你可以这样做:
let animals = ["fox", "elephant", "wolf"];
let str = "List of animals:\n"
for (let animal of animals) {
let itemNum = animals.indexOf(animal) + 1;
str += `${itemNum}: ${animal}\n`
}
alert(str)
如果你有一个对象数组,最好使用 console.table(),伙计
类似的东西:
const list = [{name: 'john', age: 10}, {name: 'misha', age: 24},{name: 'aaron', age: 50},]
console.table(Object.values(list))
我想尝试打印数组元素(动物),以便它的每个元素都在新行 (\n) 中。不幸的是,我做不到。有人可以使用我在 console.log() 中创建的逻辑来解决该问题吗?是的,我希望单个警报显示给定消息:)
let animals = ["fox", "elephant", "wolf"];
console.log("List of animals:");
for (let animal of animals) {
let itemNum = animals.indexOf(animal) + 1;
console.log(`${itemNum}: ${animal}`);
}
输出:
List of animals:
1: fox
2: elephant
3: wolf
有人能想出同样适用于 alert() 的解决方案吗?
也许你可以这样做:
let animals = ["fox", "elephant", "wolf"];
let str = "List of animals:\n"
for (let animal of animals) {
let itemNum = animals.indexOf(animal) + 1;
str += `${itemNum}: ${animal}\n`
}
alert(str)
如果你有一个对象数组,最好使用 console.table(),伙计
类似的东西:
const list = [{name: 'john', age: 10}, {name: 'misha', age: 24},{name: 'aaron', age: 50},] console.table(Object.values(list))