1:转换方法:toString(),toLocalString(),valueOf()方法。
eg:
var colors=["red","blue","black"]; console.log(colors.toString()); //red,blue,black console.log(colors.toLocaleString()); //red,blue,black console.log(colors.valueOf()); //[ 'red', 'blue', 'black' ]
console.log(colors); //[ 'red', 'blue', 'black' ]
2:栈方法: push()和pop();
3:队列方法: push() //末端添加
unshift(); //前端添加
pop(); // 移除末端
shitf();//移除前端
4:重排序方法: reverse()和sort();
5:操作方法: slice() //创建新数组,不改变原数组
splice();//改变原数组 (删除,插入,替代)
eg; array.splice(0,2);//删除数组的前两项
array.splice(2,0,"red","blue"); //从数组的位置2开始插入字符串"red"和“blue”
array.splice(2,1,"red","bule");// 删除位置2的项,再从位置2开始插入字符串
6:位置方法:indexOf()和lastIndexOf()
7:迭代方法:5个:
五个迭代方法 都接受两个参数:要在每一项上运行的函数 和 运行该函数的作用域(可选)
every():对数组中的每一项运行给定函数。如果函数对每一项都返回 true,则返回 true。
filter():对数组中的每一项运行给定函数。返回该函数会返回 true 的项组成的数组。
forEach():对数组中每一项运行给定函数。该函数没有返回值。
map():对数组中每一项运行给定函数。返回每次函数调用的结果组成的函数。
some():对数组中每一项运行给定函数。如果函数对 任一项返回 true,则返回 true
[js] view plaincopy
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
//every()和some()最相似
//every() item:当前遍历项,index:当前项索引,array:数组对象本身
var everyResult = numbers.every(function (item, index, array) {
return item > 2;
});
alert(everyResult);//false
//some()
var someResult = numbers.some(function (item, index, array) {
return item > 2;
});
alert(someResult);//true
//filter
var filterResult = numbers.filter(function (item, index, array) {
return item > 2;
});
alert(filterResult);//[3,4,5,4,3]
//map()
var mapResult = numbers.map(function (item, index, array) {
return (item * 2);
});
alert(mapResult);//[2,4,6,8,10,8,6,4,2]
//forEach 本质上和for循环没有区别
var forEachResult=numbers.forEach(function(item,index,array){
alert(item)
});
- 8:归并方法:
ECMAScript5 还新增了2个归并数组的方法:reduce()和reduceRight()。
这两个都会迭代数组的所有项
reduce():从第一项开始逐个遍历到最后。
reduceRight():从数组的最后一项开始,遍历到数组的第一项。 这两个方法都接受两个参数:在每一项上调用的函数(参数为:前一个值,当前值,项的索引,数组对象)
这个函数返回的任何值斗殴会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上,
因此第一个参数是数组的第一项,第二个参数是数组的第二项
和 作为归并基础的初始值。
使用 reduce() 方法可以执行数组中所有值之和的操作,比如:
[js] view plaincopy
var values = [1, 2, 3, 4, 5];
var sum = values.reduce(function (prev, cur, index, array) {
return prev + cur;
});
alert(sum);
//结果一样,只是方向相反而已
var sum2=values.reduceRight(function (prev,cur,index,array) {
return prev+cur;
});
alert(sum2);