-2

can I use following (PHP) Syntax to create an array in JavaScript?

$arr = ("foo" => "bar", "foobar" => "test");

I dont want to use following syntax (in JS):

var arr = [];
arr["foo"] = "bar";
arr["foobar"] = "test";

Thank you very much!

Tream
  • 1,049
  • 2
  • 13
  • 29

1 Answers1

1
var arr = {foo:"bar", foobar:"test"};

var foo = arr.foo;
var foobar = arr.foobar;
SmartDev
  • 2,802
  • 1
  • 17
  • 22
  • You really shouldn't answer questions as basic as this one. Stack Overflow is not a JS api. – Cerbrus Oct 22 '14 at 08:32
  • Thanks! The reason why I dont use objecs, is, that I cant use a variable as a key. Array: arr[key] (key is a variable). – Tream Oct 22 '14 at 08:37
  • @Tream The first thing that comes into mind is that you can use `eval()` vor variables: `eval('arr.' + key)` – SmartDev Oct 22 '14 at 08:40
  • Dude, no. Don't ever use `eval`. Especially not like that! Use `arr[key]` instead. – Cerbrus Oct 22 '14 at 08:40
  • 1
    You can also use arr[key] for objects. See http://stackoverflow.com/questions/2241875/how-to-create-object-property-from-variable-value-in-javascript – SmartDev Oct 22 '14 at 08:43
  • Arrays are objects in JavaScript. If you can access `arr[key]` in an array then you can do the same with an object. (There are no "associative arrays" in JavaScript.) – JJJ Oct 22 '14 at 08:51