接着上次的来。
稀疏数组
从0开始索引不连续的数组,length的长度大于元素的个数
var a1 = new Array(5)var a1 = []a1[1000] = 0var a2 = [,] //稀疏var a2 = [,,] //非稀疏,元素的值为undefinedvar a3 = [1,,3] //非稀疏var a3 = [1, undefined, 3] //非稀疏var a = [1, 2, 3, 4], delete a[1] //稀疏
数据的长度
[].length //0[1, 2, 3].length //3
稀疏数组的长度大于元素的个数
var a = [1, 2, 3, 4, 5]a.length = 3 //a为[1, 2, 3]a.length = 0 //a为[]a.length = 5 //a 相当于 new Array(5)Object.defineProperty(a, "length", {writable: false}; //设置a的length属性为只读,适用于ECMAScript5
数组元素的增加和删除
基本:
var a = [];a[0] = 1;a[1] = 2;
push尾部增加:
var a = [];a.push("zero");a.push(1, "5");
unshift头部增加:
a.unshift("0","sss");
对于一个使用delete不会修改数据的length属性,也不会改变数据元素的索引
var a1 = [1, 2, 3]delete a1[1]; // [1, , 3]a1.length //长度仍是3a1.pop() //返回3,数组变为[1,]a1.shift() //返回1,数组变为[ ]。即移除数组头部的一个元素,长度减1,元素索引号下移
数组遍历
for循环
function Pasta(grain, width, shape) { this.grain = grain; this.width = width; this.shape = shape; // Define a method. this.toString = function () { return (this.grain + ", " + this.width + ", " + this.shape); } } var o = new Pasta("wheat", 0.2, "circle"); // { grain: 'wheat',// width: 0.2,// shape: 'circle',// toString: [Function] }var keys = Object.keys(o); //返回对象的可枚举属性和方法的名称,["grain","width","shape","toString"]var values = [];for (var i = 0, len = keys.length; i < len; i ++) { var key = keys[i]; values[i] = o[key]; //数组的值为对象o的属性值及办法的值}for ( var i = 0; i < a.length; i ++) { if (!a[i]) continue; //跳过null, undefined和不存在的元素 if (a[i] === undefined) continue; //跳过undefined if (!(i in a )) continue; //跳过不存在的元素}
for in 循环
for (var index in sparseArray) { var value = sparseArray[index];}