标签:
//Array构造函数 var colors = new Array(); colors = new Array(20);//初始化数组容量 colors = new Array('red','blue',4)//创建包含该三项值的数组 //数组字面量表示 colors = ['name',4,true];
//移除项 var colors = ['red','green','purple']; colors.length = 2; console.log(colors[2])//undefined; //添加新项 colors[colors.length] = 'black'; colors[colors.length] = 'white'; console.log(colors);//["red", "green", "black", "white"]
//一般情况下可以使用instanceof(注意:不适用两个以上不同全局执行环境(页面包含多个框架)) console.log(['time','var'] instanceof Array);//true //推荐: if(Array.isArray(['time','var'])){ console.log("I'm array!"); }
var colors = ['red','green','white']; console.log(colors.toString());//red,green,white console.log(colors.join('-'));//red-green-white
var container = []; container.push('a','b'); console.log(container.pop());//b console.log(container.pop());//a
应用:反向输出数组的值
var container = ['a','b']; var copy = container.slice(0,container.length); while(copy.length != 0){ console.log(copy.pop()); }
var container = []; container.push('a','b'); console.log(container.shift());//a console.log(container.shift());//b //应用:使用unshift往数组前端添加项 var numContainer = ['2','3']; numContainer.unshift('1');//返回添加后数组长度 numContainer.unshift('0'); console.log(numContainer);//["0", "1", "2", "3"]
var container = ['time','money','reverse']; //1. concat 基于当前数组项拼接新数组,不影响原数组 var copy_container = container.concat();//copy of array var mix_container = container.concat('yea',['haha','liu'])//contact array console.log(mix_container);//["time", "money", "reverse", "yea", "haha", "liu"] console.log(copy_container);//["time", "money", "reverse"] //2. slice 基于当前数组截取出新数组,不影响原数组 copy_container = container.slice(0);//copy of array var slice_array = mix_container.slice(1,2);// slice of array console.log(copy_container);//["time", "money", "reverse"] console.log(slice_array);//["money"] //3. splice 影响原数组,返回值为包含删除项的数组(若无,则为空数组),有三种用法: container.splice(0,1);//删除第1项 console.log(container);//["money", "reverse"] container.splice(1,0,'lol');//把'lol'插入到位置1 console.log(container);//["money", "lol", "reverse"] container.splice(1,1,'tt','hhh');//删除位置1,然后从位置1插入两下 console.log(container);//["money", "tt", "hhh", "reverse"]
reverse()
var values = [1,2,3,4,5]; console.log(values.reverse());//[5, 4, 3, 2, 1]
sort()
sort默认情况下,按升序排列数组项,小值位于最前面,大值位于最后面,注意:sort会调用每项的toString转型方法,比较的是字符串,就算是数值,比较的也是字符串!!
var values = [0,1,5,10,15]; values.sort(); console.log(values);//[0, 1, 10, 15, 5]
自定义排序方法
var values = [0,1,5,10,15] function orderByAsc(val1,val2){ return val1 - val2; } values.sort(orderByAsc); console.log(values);//[0, 1, 5, 10, 15]
标签:
原文地址:http://www.cnblogs.com/ZHeGeS/p/JavaScript-zhiArray-lei-xing.html