"aaa", "2" => "bbb", "3" => "ccc" -6ren">
gpt4 book ai didi

javascript - 将二维数组从 PHP 转换为 JS

转载 作者:行者123 更新时间:2023-11-30 20:14:16 24 4
gpt4 key购买 nike

假设我在 PHP 中有这样的二维数组:

<?php
$db = array(
"1" => array(
"1" => "aaa",
"2" => "bbb",
"3" => "ccc"
),
"2" => array(
"1" => "ddd",
"2" => "eee"
),
"3" => array(
"1" => "fff",
"2" => "ggg",
"3" => "hhh"
)
);
?>

我想将它转换为 JS,是的,我可以这样做:

var db = new Array(3);
db[1][1] = "aaa";
db[1][2] = "bbb";
db[1][3] = "ccc";
db[2][1] = "ddd";
db[2][2] = "eee";
db[3][1] = "fff";
db[3][2] = "ggg";
db[3][3] = "hhh";

在 JS 中初始化数组有点难看,有没有更好的方法像在 PHP 中那样初始化它?

最佳答案

js也可以一行初始化数组:

var db = [["aaa", "bbb", "ccc"], ["ddd", "eee", "fff"], ["ggg", "hhh", "iii"]]

实际上很少看到 new Array() 符号(在阅读您的问题之前我已经忘记了它)

好处:这种声明数组的方式在 php 中也是正确的

$db = [["aaa", "bbb", "ccc"], ["ddd", "eee", "fff"], ["ggg", "hhh", "iii"]];

关于javascript - 将二维数组从 PHP 转换为 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com