Array在Javascript程序开发中是一个经常使用到。一个数组可以存储Javascript支持的任何数据类型。
1.基本知识点
//创建一个对象并初始化它
var preInitArray = new Array("First Item", "Second Item", "Third Item");
for (var i = 0; i < preInitArray.length; i++) {
console.log(preInitArray[i]);
}
//保存一定数目的数据项
var preArray = new Array(3);
//创建一个空的数组,长度未指定
var anArray = new Array();
//为元素赋值来为数组添加新的数据项
anArray[0] = "First Item";
anArray[1] = "Second Item";
anArray[2] = "Third Item";
//数组的简写方式
var myArray = [1, 2, 3];
var yourArray = ["Red","White","Blue"];
<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->
2.数组的复制操作。今天项目中需要使用一个临时数组。我使用如下方法:
var myArray = new Array(20, 40, 50, 10);
var tempArray = myArray;
//然后使用sort()方法排序
tempArray.sort();
//然后索引输出myArray里面的值,发现myArray也排序了。
for (var j = 0; j < myArray.length; j++) {
console.log(j + ":" + myArray[j]);
//输出结果:
/*
0:10
1:20
3:50
*/
}
发现myArray数组也进行了排序,其实Javascript中数组对象都是引用类型的,所以tempArray排序之后,myArray里面的数据也进行了相应的排序。所以得到没有得到自己预期的结果。改动一下代码进行数组间的复制操作。
//完成数组之间的复制操作
for (var i = 0; i < myArray.length; i++) {
tempArray[i] = myArray[0];
}
<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->
在完成程序功能后,我查询了一些资料,有三种常见的方法在Javascript中进行数组复制操作,每个方法的性能在各个浏览器中还有很大的不同。下一篇介绍Javascript中数组操作的三种方法及性能测试。
<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->