-1

how to write an array literal notation in JS?

var myArray = new Array();
myArray.prop = 'test';

i've already tried this, but it logs undefined value.

var myArray = [prop='test'];
console.log(myArray.prop);
user2271066
  • 61
  • 1
  • 2

2 Answers2

1

The array literal is:

['foo', 'bar', 'baz']

You cannot use keys in this, because Javascript arrays do not have string keys. They're numerically indexed lists. Setting a property on an array object does not do what you think it does.

What you're looking for is an object literal:

{ foo : 'bar', baz : 42 }
deceze
  • 510,633
  • 85
  • 743
  • 889
  • ahh, thanks for the help, i'm still learning the basic, and btw i got this from http://jsfiddle.net/javascriptenlightenment/RuQfJ/ – user2271066 Oct 12 '13 at 06:19
  • Unless that's an example of what not to do/unexpected results, you should not follow that tutorial/site/whateverthatisfrom anymore. – deceze Oct 12 '13 at 06:25
0

Arrays in JavaScript cannot have string indices... they must be numbers. What you're looking for in your case is an object.

var myObject = {
    prop: 'test'
}
Brad
  • 159,648
  • 54
  • 349
  • 530