0

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!

1 Answer 1

2

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]}]);
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.