1

I've noticed something weird. I've always thought new Array() was the same as {}, however it seems to be different as {} seems to just be an object type whereas new Array() is an Array in the Chrome debugger.

So I've been using $.param(data), where data is the data from a $.ajax() call. I notice that when i have a params1 = new Array() and a params2 = {} inside the data, they come out differently.

params1 becomes

params1[]=1&params1[]=2 

and params2 becomes

params2[0]=1&params2[1]=2.

The problem is that I had been using .param(data, false) because I noticed that params1[] was being serialized incorrectly, however .param(data, false) fails for params2 and gives me params2=[object+Object].

I figure I can get around this by just using .param(data) and stripping out "[]" so that regardless of it being initialized using {} or new Array, it'll still work out correctly. But I'd like to know if there's a better solution (short of always using {} vs new Array).

2
  • 4
    [] is shorthand for creating a new JavaScript array, not {}. As you already saw, {} creates an empty object. Commented Aug 8, 2012 at 20:03
  • possible duplicate of Create an empty object in JavaScript with {} or new Object()? Commented Aug 9, 2012 at 19:17

1 Answer 1

1

Kyliod,

In javascript {} is shorthand for creating a new Object, and [] is shorthand for a "new Array()."

SO:

var myArray1 = [];
var myArray2 = new Array();
var myObject = {};
myObject.objVariable1 = 'some string or other variable data';
var myObject2 = { obj2Var1 : 'some string', obj2Var2 : 1234, obj2Var3 : true };

// do stuff

var thing1 = myArray1[1]; // get something out of myArray1
var thing2 = myArray2[2]; // get something out of myArray2
var thing3 = myObject.objVariable1; // get something out of myObject
if(myObject2.obj2Var3)
{
  // do other stuff
}

Hopefully this helps you clear up your jQuery / javascript Ajax issues.

Sign up to request clarification or add additional context in comments.

Comments

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.