简体   繁体   English

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

[英]How to print array inside array using JavaScript

The task is to create the following array of arrays in JavaScript:任务是在 JavaScript 中创建以下 arrays 数组:

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

It actually printing output but not inside the bracket.它实际上打印 output 但不在支架内。 Please help.请帮忙。

for(let i = 0; i < webTechs.length; i++){
    arr.push(webTechs[i], webTechs[i].length)
}
console.log(arr)

As what you're expecting is an array of arrays, you need to push the elements as arrays themselves:正如您所期望的是 arrays 数组,您需要将元素推送为 arrays 本身:

    for(let i = 0; i < webTechs.length; i++){
        arr.push([webTechs[i], webTechs[i].length]) //Notice the [] to push them as array into 'arr'
    }

在此处输入图像描述 arr.push([webTechs[i], webTechs[i].length]) this is what you are looking for i guess. arr.push([webTechs[i], webTechs[i].length]) 这就是你要找的我猜。

EXPLANATION解释

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

BUT

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

USING JSON.stringify使用 JSON.stringify 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM