在本系列教程三中,我们提到,JS中的对象有三大类:
接下来我们就说一下内建对象中的数组(Array)
var arr = new Array();
//使用typeof检查一个数组时,
console.log(typeof arr); //返回object
/*
向数组中添加元素
语法:数组[索引] = 值
*/
arr[0] = 10;
arr[1] = 33;
arr[2] = 22;
arr[3] = 44;
console.log(arr[3]);
console.log(arr.length);
修改length
arr.length = 10;
可以在创建时就指定数组中的元素
var arr = [1,2,3,4,5,10];
数组中的元素可以是任意的数据类型,也可以是对象,也可以是一个函数,也可以是一个数组
arr = ["hello",1,true,null,undefined]; //各种类型
arr = [{
name:"孙悟空"},{
name:"沙和尚"},{
name:"猪八戒"}]; //对象
arr = [function(){
alert(1)},function(){
alert(2)}]; //函数
arr = [[1,2,3],[3,4,5],[5,6,7]]; //数组,这种也称二维数组
使用构造函数创建数组
也可以同时添加元素,将要添加的元素作为构造函数的参数传递;元素之间使用逗号‘,‘隔开。
var arr2 = new Array(10,20,30);
console.log(arr2);
注意以下区别
// 创建一个数组,数组只有一个元素10
arr = [10] ;
// 创建一个长度为10的数组
var arr2 = new Array(10);
// 创建一个数组
var arr = ["孙悟空"];
var result = arr.push("唐僧","蜘蛛精","白骨精","玉兔精");
console.log(arr); //"孙悟空","唐僧","蜘蛛精","白骨精","玉兔精"
console.log("result = "+result); //result=5
result = arr.pop();
console.log("result = "+result); //result="玉兔精"
arr.unshift("牛魔王","二郎神");
console.log(arr); //,"二郎神","孙悟空","唐僧","蜘蛛精","白骨精"
console.log("result = "+result); //result=6
result = arr.shift();
console.log(arr); // "二郎神","孙悟空","唐僧","蜘蛛精","白骨精"
console.log("result = "+result); //result="牛魔王"
// 创建一个数组
var arr = ["孙悟空","猪八戒","沙和尚"];
// 循环遍历
for(var i=0 ; i<arr.length ; i++){
console.log(arr[i]);
}
注:这个方法只支持IE8以上的浏览器,IE8及以下的浏览器均不支持该方法,所以如果需要兼容IE8,则不要使用forEach,还是使用for循环来遍历
//创建一个数组
var arr = ["孙悟空","猪八戒","沙和尚","唐僧","白骨精"];
arr.forEach(function(value, index , obj){
console.log("value = "+value);
console.log("index = "+index);
console.log(arr==obj);
});
//创建一个数组
var arr = ["孙悟空","猪八戒","沙和尚","唐僧","白骨精"];
参数:
var result = arr.slice(0,2);
console.log(result); //孙悟空,猪八戒
result = arr.slice(1);
console.log(result); //猪八戒,沙和尚,唐僧,白骨精
result = arr.slice(1,-2); //从第一个截到倒数第二个,且不包括倒数第二个
console.log(result); //猪八戒,沙和尚
console.log(arr); //arr还是arr,不会变 "孙悟空,猪八戒,沙和尚,唐僧,白骨精"
arr = ["孙悟空","猪八戒","沙和尚","唐僧","白骨精"];
//猪八戒被删除,在猪八戒前面插入"牛魔王","铁扇公主","红孩儿"
var result = arr.splice(1,1,"牛魔王","铁扇公主","红孩儿");
console.log(arr); //["孙悟空", "牛魔王", "铁扇公主", "红孩儿", "沙和尚", "唐僧", "白骨精"]
console.log(result); //["猪八戒"]
var arr = ["孙悟空","猪八戒","沙和尚"];
var arr2 = ["白骨精","玉兔精","蜘蛛精"];
var arr3 = ["二郎神","太上老君","玉皇大帝"];
var result = arr.concat(arr2,arr3,"牛魔王","铁扇公主");
var arr = ["孙悟空","猪八戒","沙和尚","唐僧"];
var result = arr.join();
console.log(typeof result); //string
arr = ["孙悟空","猪八戒","沙和尚","唐僧"];
result = arr.join("@-@");
console.log(result);
arr = ["孙悟空","猪八戒","沙和尚","唐僧"];
arr.reverse();
console.log(arr); // ["唐僧", "沙和尚", "猪八戒", "孙悟空"]
arr = ["b","d","e","a","c"];
arr1 = [3,4,11,2,5];
arr.sort();
console.log(arr); //["a", "b", "c", "d", "e"]
arr1.sort();
console.log(arr1); //[11,2,3,4,5]
我们可以自己来指定排序的规则
/*
* 如果需要升序排列,则返回 a-b
* 如果需要降序排列,则返回 b-a
*/
arr = [5,4,2,1,3,6,8,7];
arr.sort(function(a,b){
//升序排列
//return a - b;
//降序排列
return b - a;
});
console.log(arr); //[8, 7, 6, 5, 4, 3, 2, 1]