日期:2014-05-16  浏览次数:20492 次

JS-Array类小总结

?Array类:

?

?

?

首先 ^^

数组定义习惯上都用 [], 下面分别使用 new Array() [] ,验证时间效率代码如下,看看谁用的时间少:

var a = new Date ;
var arr, direct, b = [];
for(var i=0; i<10000; i++)
 arr = new Array();
b.push(new Date() - a);
a = new Date;
for(var i=0; i<10000; i++) 
direct = [];
b.push(new Date() - a);
alert(b.join(" : "));

?

以下总结参考 JS 高级程序设计

1 创建 Array 类对象:

?

(1)	
var numbers= new Array();//习惯上是var numbers= [];
numbers [0] = "one";
numbers [2] = "two";
numbers [3] = "three";
numbers [35] = "four";
alert(numbers [0]);     //outputs “one”
alert(numbers [35]);   //outputs ”four”
alert(numbers.length);  //outputs “36”

?

(2)
var numbers= new Array(15);// 习惯上是var numbers= [15];
alert(numbers [0]);        //outputs "undefined"
alert(numbers.length);    //outputs "15"

?

(3)
var numbers= new Array("one","two","three");//习惯上是var numbers= ["one","two","three"];
alert(numbers [0]);      //outputs "undefined"
numbers [10] = "four";
alert(numbers.length);    //outputs "11"

?

(4)用字面量表示定义Array对象:

var numbers= ["one","two","three"];
alert(numbers [0]);      //outputs "undefined"
numbers [10] = "four";
alert(numbers.length);     //outputs "11"

?

?? 2? Array 对象覆盖 toString() 方法和 valueOf() 方法,返回字符串。

var numbers= ["one","two","three"];
alert(numbers.toString());  //outputs "one,two,three"
alert(numbers.valueOf());  //outputs "one,two,three"

?

3? toLocalString() 方法。

?

var numbers= ["one","two","three"];
alert(numbers.toLocaleString());  //outputs "one,two,three"

?

4? join() 方法,,用来连接字符串的值。

var numbers= ["one","two","three"];
alert(numbers.join(","));  //outputs "one,two,three"
alert(numbers.join("-and-"));  //outputs "one-and-two-and-three"
alert(numbers.join(""));  //outputs "onetwothree"
alert(numbers.join(")("));  //outputs "one)(two)(three"

?

? 5? concat() 方法。

var numbers= ["one","two","three"];
var arr = numbers;
var numbers2=arr.concat("four","five");
alert(numbers2.toString());     //outputs "one,two,three,four