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

JavaScript基础之数组使用技巧(转)

?<wbr></wbr>?<wbr></wbr>?<wbr></wbr>JavaScript 数组使用技巧

?<wbr></wbr>?<wbr></wbr>
?<wbr></wbr>?<wbr></wbr>?<wbr></wbr>
//创建数组, 长度由后期赋值决定
?<wbr></wbr> ?<wbr></wbr> var arry1 = new Array;
?<wbr></wbr> ?<wbr></wbr> for (i = 0; i < 5; i++) {
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr>?<wbr></wbr>arry1 = 2 * i + 1;
?<wbr></wbr> ?<wbr></wbr> }

?<wbr></wbr> ?<wbr></wbr> // length属性, 返回数组的长度
?<wbr></wbr> ?<wbr></wbr> alert("arry1.length=" + arry1.length);
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // toString()方法, 返回数组的字符串表示
?<wbr></wbr> ?<wbr></wbr> alert("arry1=" + arry1.toString());
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // 构建数组并初始化, 有点像Java
?<wbr></wbr> ?<wbr></wbr> arry2 = [2, 4, 6, 8];
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // concat方法, 用于连接两个数组
?<wbr></wbr> ?<wbr></wbr> var arry3 = arry1.concat(arry2);
?<wbr></wbr> ?<wbr></wbr> alert(arry3); // 1, 3, 5, 7, 9, 2, 4, 6, 8
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // concat的另外一种用法, 可以有多个参数
?<wbr></wbr> ?<wbr></wbr> var arry4 = arry2.concat(1, 3, 5, 7, 9);
?<wbr></wbr> ?<wbr></wbr> alert(arry4); // 2, 4, 6, 8,?<wbr></wbr>?<wbr></wbr>1, 3,?<wbr></wbr>?<wbr></wbr>5,?<wbr></wbr>?<wbr></wbr>7,?<wbr></wbr>?<wbr></wbr>9
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // join方法, 用于将数组中的各个元素连接成字符串
?<wbr></wbr> ?<wbr></wbr> var arry5 = ["one", "two", "three"];
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr> ?<wbr></wbr>
?<wbr></wbr> ?<wbr></wbr> // 默认用","连接
?<wbr></wbr> ?<wbr></wbr> var strArry = arry5.join();
?<wbr></wbr> ?<wbr></wbr> alert(strArry); // "one,two,three"
?<wbr></wbr> ?<wbr></wbr>?<wbr></wbr