如何使用JavaScript在数组中打印数组

问题描述 投票:1回答:2

任务是用JavaScript创建以下数组。

[
    ["HTML", 4],
    ["CSS", 3],
    ["JavaScript", 10],
    ["React", 5],
    ["Redux", 5],
    ["Node", 4],
    ["MongoDB", 7]
]

它实际上是打印输出,但不是在括号内。请帮助我们。

for(let i = 0; i < webTechs.length; i++){
    arr.push(webTechs[i], webTechs[i].length)
}
console.log(arr)
javascript arrays for-loop push
2个回答
0
投票

enter image description here arr.push([webTechs[i], webTechs[i].length])这就是你要找的东西吧。

解释

  • arr.push("a", "apple") ==> ["a", "apple"]

但是

  • arr.push(["a", "apple"]) ==> [["a", "apple"]] 。

使用JSON.stringifyenter image description here


0
投票

由于你期待的是一个数组,你需要把元素本身作为数组推送。

    for(let i = 0; i < webTechs.length; i++){
        arr.push([webTechs[i], webTechs[i].length]) //Notice the [] to push them as array into 'arr'
    }
© www.soinside.com 2019 - 2024. All rights reserved.