【问题标题】:How to use alert() to show elements of array in JS?如何使用 alert() 在 JS 中显示数组元素?
【发布时间】:2021-02-10 01:24:00
【问题描述】:

我想尝试打印数组(动物)的元素,以便它的每个元素都在新行(\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() 的解决方案吗?

【问题讨论】:

  • 那么您当前的解决方案有什么问题?
  • 这能回答你的问题吗? Alert an array with while loop
  • 此解决方案没有任何问题。我想在 alert() 方法中使用相同的逻辑。我该怎么做?和 padaleiana 不,它没有..

标签: javascript for-loop alert


【解决方案1】:

也许你可以这样做:

    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)

【讨论】:

  • 创意 :) 谢谢老兄!
  • alert(animals.map((a, i) => `${i + 1): ${a}`).join('\n'))(但至少要考虑一个中间常量)。
  • 同意我只是让其与他的设置方式相似
【解决方案2】:

如果你有一个对象数组,最好使用 console.table(),伙计

类似的东西:

const list = [{name: 'john', age: 10}, {name: 'misha', age: 24},{name: 'aaron', age: 50},]
console.table(Object.values(list))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2021-12-04
    相关资源
    最近更新 更多