开发者

Javascript - What's the difference with this object definiton notations?

I'm trying to pass an array to jquery's .ajax() function's开发者_如何学编程 data parameter. The first approach is that I made my 2-dimensional array like this:

var arr = new Array();
for(i in someArray){
      arr[i] = new Array();
  arr[i].lon = "x";
  arr[i].lat = "y";
}

Then I try to pass this as data in $.ajax():

$.ajax({
    data: { vals : arr },
    async: false,
    type: "POST",
    url: "namedb.php",
    dataType: "script",
    success: function(data){
      result = data;
      alert(result);
        }
});

test.php just returns all the values of $_POST. So alert() here returns:

Array
(
)

But if I changed the code to:

var arr = new Array();
for(i in someArray){
      arr[i] = new Array();
  arr[i] = { lon: "x", lat: "y" };
}

the alert() returns what I expected:

Array
(
    [vals] => Array
        (
            [0] => Array
                (
                    [lat] => "y",
                    [lon] => "x"
                )
            ...
        )
)

I know that both methods initializes the variables/attributes of each element of arr (or am I wrong?). But why do the 2 approach behaves differently? (Sorry I could've shorten my question, but I guess I need to explain how I found it).

EDIT: I had added the initialization (arr[i] = new Array();). I must have erased it during the editing of the question. But still the same problem.


That is because you did not initialize the array elements.

var arr = new Array();
for(i in someArray){
  arr[i] = {}; // initialize it!
  arr[i].lon = "x";
  arr[i].lat = "y";
}

Actually, I prefer to write

var arr = new Array();
for(i in someArray){
  arr[i] = { lon: "x", lat: "y" };
}

Because I don't have to type arr[i] 3 times.


Using for in loops over an array is wrong, you should use for loops or jQuery's $.each

var arr = [];
for(var i = 0; i < someArray.length; i ++) {
  arr[i] = { lon: "x", lat: "y" };
}

Or

var arr = [];
$.each(someArray, function(i, value) {
  arr[i] = { lon: "x", lat: "y" };
});

Using Array.prototype.push for adding things to an array is easier, because you don't need to know the next index of an array, also compare with arr[arr.length]=something.

var arr = [];
$.each(someArray, function(i, value) {
  arr.push({ lon: "x", lat: "y" });
});

And now what you're doing is collect data from an array and translate it into another array. jQuery already has a function that does this: $.map.

var arr = $.map(someArray, function(value, i) {
  return { lon: "x", lat: "y" };
});

Note that when using $.each, the arguments are i, value, when you use $.map, they are switched.


var arr = new Array();
for(i in someArray){
  arr[i].lon = "x";
  arr[i].lat = "y";
}

Gives error. Because arr[i] is always undefined for any i.

In second case you are creating a new Object and assign it to arr[i]


The problem is that in your first approach you are not initializing arr[i] to an object before trying to set its properties. Indeed, I think you should be getting JavaScript errors in the debug console. The following would work:

var arr = new Array();
for(i in someArray){
  arr[i] = {}; // or "new Object()"
  arr[i].lon = "x";
  arr[i].lat = "y";
}

FYI using new Array() is bad practice; it's better to use var arr = []. Similarly that's why I used arr[i] = {} instead of arr[i] = new Object().

EDIT In light of your edit, you added the line arr[i] = new Array(). Well, arrays don't have lon and lat properties, so trying to set them will not work! You need to use arr[i] = new Object() or (better) arr[i] = {}. Only objects get "expando properties," where you just assign things to myObject.propertyName and the object suddenly has a propertyName property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜