当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript 有趣而诡异的数组

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript 有趣而诡异的数组


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 359 ::
收藏到网摘: n/a

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

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);
}

扩展阅读: