[英]PHP to Javascript Multidimensional Array
I have some php code that I am trying to rewrite in Javascript. 我有一些PHP代码试图用Javascript重写。 When I run my original JS code through a debugger it does not like my extra brackets (see below).
当我通过调试器运行原始JS代码时,它不喜欢我的多余括号(请参见下文)。
EDIT : The PHP works great FYI. 编辑 :PHP的效果很好。
PHP: PHP:
<?php
$g = array( array("H", "T", 1), array("L", "M", 4), array("U", "V", 6) );
$v = array();
$n = array();
foreach ($g as $item) {
array_push($v, $item[0], $item[1]);
$n[$item[0]][] = array("final" => $item[1], "cost" => $item[2]);
$n[$item[1]][] = array("final" => $item[0], "cost" => $item[2]);
}
?>
Now I'm trying to convert the code above into Javascript. 现在,我正在尝试将上面的代码转换为Javascript。 The debugger errors out on the
[]
on line 调试器错误在
[]
行上显示
n[item[0]][] = [{"final"...
The error says Unexpected token ]
错误显示“
Unexpected token ]
it does not like the extra brackets after the array. 它不喜欢数组后的多余括号。 But I'm not sure how else I am supposed to describe the array?
但是我不确定我还应该如何描述数组? Can someone help?
有人可以帮忙吗?
Javascript: Javascript:
var g = [ ["H", "T", 1], ["L", "M", 4], ["U", "V", 6] ];
var v = [];
var n = [];
g.forEach(function(item) {
v.push(item[0], item[1]);
n[item[0]][] = [{"final": item[1], "cost": item[2]}];
n[item[1]][] = [{"final": item[0], "cost": item[2]}];
});
Any help is greatly appreciated! 任何帮助是极大的赞赏!
The problem is in the brackets []. 问题出在方括号[]中。 This notation works in PHP but not in JavaScript.
此表示法在PHP中有效,但在JavaScript中不适用。 To do this use the push method.
为此,请使用push方法。 Look:
看:
var g = [ ["H", "T", 1], ["L", "M", 4], ["U", "V", 6] ];
var v = [];
var n = [];
g.forEach(function(item) {
v.push(item[0], item[1]);
n[item[0]].push([{"final": item[1], "cost": item[2]}]);
n[item[1]].push([{"final": item[0], "cost": item[2]}]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.