简体   繁体   中英

PHP to Javascript Multidimensional Array

I have some php code that I am trying to rewrite in Javascript. When I run my original JS code through a debugger it does not like my extra brackets (see below).

EDIT : The PHP works great FYI.

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. The debugger errors out on the [] on line

n[item[0]][] = [{"final"...

The error says 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:

 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. To do this use the push method. 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]}]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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