JavaScript Arrays: The Difference Between [] and { }
Using Moo 1.2 has taught me a lot about JavaScript. Of course, that means I've made a lot of mistakes but that seems to be the best way for me to learn. While browsing the Moo source, I'd always wondered the difference between arrays using brackets ([]) and braces ({}). Here's what I learned.
Use brackets for an array of simple values.
//examples var answers = ['yes','no','maybe']; var names = ['David','Kristina','Charlie','Angela'];
Use braces for key => value arrays and objects/properties.
//example - random array
var programmer = { 'name':'David Walsh', 'url':'http://davidwalsh.name', 'girl':'Kristina'}
//example - used for an object's properties
var Element.implement({
getText: function(){
return this.get('text');
}
});This is similar to PHP's array system.
$arr = array('name'=>'David','position'=>'Programmer');Have anything to add? Please share!
Discussion
Be Heard!
Share your thoughts with fellow developers of all skill levels! I want to hear from you!
This is interesting. So if you use []‘s in a key=>value array it just won’t work or it’s simply improper usage?
I must admit, I’ve wondered this myself with the MOO as they seem to have pretty creative looking code conventions (that really make a lot of sense).
@Tim: That’s what I get from it. Please let me know if I’m wrong.
I feel like you’re missing one of the finer points in this bracket/brace post; braces define Objects – not Arrays!
The following are essentially the same:
var myArray = [];
var myArray = new Array();
… as are:
var myObject = {};
var myObject = new Object();
Javascript is by no means perfect – so you’ll have to know the pitfalls, like erroneously mixing keys and indexes in an Array (like you can do in PHP – bad).
As javascript doesn’t have associative arrays Objects are the closest thing.
Thanks David
U solved my problem. I am first time using Javascript in my website and i was getting one problem with one line.
mycarousel_itemList[counter]=
[{url: "ID,'thumbnail', true); ?>",link: "",title: ""}]
;
and u solved it … thanks again…regards