Array 对象方法分类:1、可以改变原数组 2、 不可以改变原数组
1、不可以改变原数组
(1)concat()方法:连接两个或更多的数组,并返回结果。
var arr = ["bbb","aaa","ccc"]; arr.concat(4,5); console.log(arr.concat(4,5));// ["bbb", "aaa", "ccc", 4, 5] console.log(arr);//["bbb", "aaa", "ccc"]
(2)join() 把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。
var arr = ["bbb","aaa","ccc"]; arr.join(); console.log(arr.join()) //bbb,aaa,ccc console.log(arr) //["bbb", "aaa", "ccc"]
(3)slice() 从某个已有的数组返回选定的元素
var arr = ["bbb","aaa","ccc"]; console.log(arr.slice(1))//["aaa", "ccc"] console.log(arr)//["bbb", "aaa", "ccc"]
(4)toSource() 方法表示对象的源代码。(只有 Gecko 核心的浏览器(比如 Firefox)支持该方法,也就是说 IE、Safari、Chrome、Opera 等浏览器均不支持该方法。)
function employee(name,job,born){ this.name=name; this.job=job; this.born=born; } var bill = new employee("Bill Gates","Engineer",1985); document.write(bill.toSource()); //({name:"Bill Gates", job:"Engineer", born:1985}) document.write(bill); // Object { name: "Bill Gates", job: "Engineer", born: 1985 }
(5)toString() 方法可把数组转换为字符串,并返回结果。
var arr = [1,2,3,"zhang"]; console.log(arr.toString()) //1,2,3,zhang console.log(arr) // (4) [1, 2, 3, "zhang"]
(6)toLocaleString() 把数组转换为本地字符串。
var arr = ["bbb","aaa","ccc"]; console.log(arr.toLocaleString()) //bbb,aaa,ccc console.log(arr)// (3) ["bbb", "aaa", "ccc"]
(7)valueOf() 方法返回 Array 对象的原始值。
var arr1 = [{name:"jack"},1,"333"] console.log(arr1.valueOf()); //(3) [{…}, 1, "333"] console.log(arr1) //(3) [{…}, 1, "333"]
2、可以改变原数组
(1)pop() 删除并返回数组的最后一个元素
var arr = ["bbb","aaa","ccc"]; console.log(arr.pop()); //aaa console.log(arr); //(2) ["bbb", "aaa"]
(2)push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
var arr = ["bbb","aaa","ccc"]; console.log(arr.push("ddd")) //4 console.log(arr) //(4) ["bbb", "aaa", "ccc", "ddd"]
(3)reverse() 颠倒数组中元素的顺序。
var arr = ["bbb","aaa","ccc"]; console.log(arr.reverse()); //(3) ["ccc", "aaa", "bbb"] console.log(arr)//(3) ["ccc", "aaa", "bbb"]
(4)shift() 删除并返回数组的第一个元素
var arr = ["bbb","aaa","ccc"]; console.log(arr.shift()) //bbb console.log(arr) //(2) ["aaa", "ccc"]
(5)sort() 对数组的元素进行排序
var arr = ["bbb","aaa","ccc"]; console.log(arr.sort()) //(3) ["aaa", "bbb", "ccc"] console.log(arr) //(3) ["aaa", "bbb", "ccc"]
(6)splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
var arr = ["bbb","aaa","ccc"]; console.log(arr.splice(2,0,"ddd")) //[] console.log(arr) // (4) ["bbb", "aaa", "ddd", "ccc"]
(7)unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。
var arr = ["bbb","aaa","ccc"]; console.log(arr.unshift("ddd")) //4 console.log(arr) // (4) ["ddd", "bbb", "aaa", "ccc"]