开发者

JavaScript array's length method

开发者 https://www.devze.com 2023-02-18 10:50 出处:网络
Can anyone explain why the second alert says 0 ? var pollData = new Array(); pollData[\'pollType\'] = 2;

Can anyone explain why the second alert says 0 ?

  var pollData = new Array();
  pollData['pollType'] = 2;
  alert(pollData['pollType']); // This prints 2
  alert(pollData.length); // This prints 0开发者_StackOverflow中文版 ??


The length of the array is only changed when you add numeric indexes. For example,

pollData["randomString"] = 23;

has no effect on length, but

var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46

changes the length to 46. Note that it doesn't matter if the key was a number or a string, as long as it is a numeric integer.

Besides, you are not supposed to use arrays in this manner. Consider it more of a side effect, since arrays are objects too, and in JavaScript any object can hold arbitrary keys as strings.


Because you haven't put anything into the array yet. You've only been assigning to a dynamically-created pollType attribute on the array object.

If you use numeric indices, then the array automagically takes care of length. For example:

var arr = [  ];    // same as new Array()
arr[2] = 'Banana!';
alert(arr.length);    // prints 3 (indexes 0 through 2 were created)


The length property takes into consideration only those members of the array which names are indexes (like '1', '2', '3', ... ).


Arrays in JavaScript have numeric indexes only.

Use an object, which is essentially what you are doing above, setting properties on that array object.


array.length returns how many values are stored in the array. The first alert is returning the value of the position 'pollType'.

The reference guide I always use when needing help with javascript arrays is this page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

I'd also read what it says under the heading Javascript Does Not Support Associative Arrays, as you may run into problems with this also.


var pollData = Array();

function test() {
    pollData[0] = 2
    alert(pollData[0]);
    alert(pollData.length);
}

//[x] is the array position; hence ['polltype'] is causing issues

0

精彩评论

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