javascript 有趣而诡异的数组

  年前在重写淘宝旺铺里的会员卡脚本的时候,无意中发现了一个有趣的事情。代码类似:

  

复制代码 代码如下:

  var associative_array = new Array();

  associative_array["one"] = "1";

  associative_array["two"] = "2";

  associative_array["three"] = "3";

  if(associative_array.length > 0)

  { // to do}

  会发现 associative_array.length 始终等于 0,当时有点迷惑,后来才知道这就像大家认为 IE 中支持 CSS 属性 display:inline-block 一样,纯属巧合和误解。

  

  实际上(引自《JavaScript “Associative Arrays” Considered Harmful》):

  JavaScript arrays (which are meant to be numeric) are often used to hold key/value pairs. This is bad practice. Object should be used instead.

  //大意:数组只支持数字的,键值对应使用于对象上。

There is no way to specify string keys in an array constructor. //在数组构造函数中无法定义字符串键值

  There is no way to specify string keys in an array literal. //在数组字面量中无法定义字符串键值

  Array.length does not count them as items. // Array.length 不会计算字符串键值

  进一步窥探数组:

  1、数组可以根据所赋的值自动调整大小

  

复制代码 代码如下:

  var ar = [];

  ar[2] = 1;

  alert(ar.length)

  发现这个数组的长度为 3,就像一个经过初始化的数组一样。所有没有赋值的数组对象,都将被定义为 undefined 。

  

  扩展阅读:

  2、可使用 “The Miller Device” 方法来判断是否是数组

复制代码 代码如下:

  function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]';}

  “The Miller Device” 的妙用不仅仅在于判断数组:

  

复制代码 代码如下:

  var is = {

  types : ["Array","RegExp","Date","Number","String","Object"]

  };

  for(var i=0,c;c=is.types[i++];){

  is[c] = (function(type){

  return function(obj){

  return Object.prototype.toString.call(obj) == “[object "+type+"]“;

  }

  })(c);

  }

  

  扩展阅读: