创建数组
var a=new Array(元素1,元素2,元素3,元素4,........)
var a=[1,2,3,4];
遍历数组的元素
1) for 循环
(2) while();
(3) for...in 循环将遍历对象的所有可枚举属性。//for in更适合遍历对象,不要使用for in遍历数组
for(var i in a)
{document.write(a[i]+"|");} //1|2|3
使用for in 也可以遍历数组,但是会存在以下问题:
1.index索引为字符串型数字,不能直接进行几何运算
2.遍历顺序有可能不是按照实际数组的内部顺序
3.使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性
所以for in更适合遍历对象,不要使用for in遍历数组。
Array.prototype.method=function(){
console.log(this.length);
}
var myArray=[1,2,3]
myArray.name="数组"
for (var index in myArray) {
console.log(myArray[index]);
}
输出:
1 2 3
数组
function(){
console.log(this.length);
}
for of遍历的只是数组内的元素,可以在开发过程中节省大量的时间。
(5)forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身
因此:
[].forEach(function(value,index,array){
//code something
});
map
map即是 “映射”的意思 用法与 forEach 相似,用法即:
map则是对原数组的加工,映射成一一映射的新数组
[].map(function(value,index,array){
//code
})
let arr = [1, 2, 3, 4];
let newArr = arr.map(function(item) {// 使用map方法
return item * 2;
});
console.log(newArr);
filter是满足条件的留下,是对原数组的过滤;
let arr = [1, 2, 3, 4];
let newArr = arr.filter(function(item) {// 使用filter方法
return item % 2 !== 0;
});
console.log(newArr); // [1, 3];
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终为一个值(reduce和reduceRight
)
arr.reduce(callback,[initialValue])
callback (执行数组中每个值的函数,包含四个参数)
previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
currentValue (数组中当前被处理的元素)
index (当前元素在数组中的索引)
array (调用 reduce 的数组)
initialValue (作为第一次调用 callback 的第一个参数。)
var items = [2, 4, 6];
var go = items.reduce(function(total, num){
return total + num},1)
console.log(go); //13
方法 | 作用 | 返回 | 例子 |
concat(数组元素 ) | 连接两个或更多的数组 | 返回结果
| document.write(a.concat(b)); //1,2,3,a,b,c |
reverse( ) | 颠倒数组中元素的顺序 | 返回新数组 | b.reverse() alert(b); //c,b,d |
.slice(start,end) | 截取数组开始到结束位置的元素,支持负数 | 返回新数组 | document.write(a.slice(0,2)); //1,2 |
.splice(start,length,替换的元素...) | 删除元素,并向数组添加新元素,数组改变 | 如果有删除的元素,返回删除的元素 | document.write(b.splice(1,2,"f","f")); alert(b); //b,c //a,f,f |
.pop( ) | 删除数组的最后一个元素,数组改变 | 返回删除的元素 | documnet.write(b.pop()); //c |
.shift( ) | 删除并返回数组的第一个元素,数组改变 | 第一个元素 | b.shift(); alert(b); //b,c |
.unshift( ) | 向数组的开头添加一个或更多元素数组改变 | 并返回新的长度 | document.write(b.unshift("1")); alert(b); //4 //1,a,b,c
|
.push( ) | 向数组的末尾添加一个或更多元素,数组改变 | 并返回新的长度 | document.write(b.push("1")); alert(b); //4 //a,b,c,1 |
.join([分隔符]) | 把元素按分隔符组合成字符串,默认分隔符“,” | 字符串 | document.write(a.join("|")); //1|2|3 |
toString( ) | 把数组转换为字符串 | 并返回结果 | document.write(b.toString()); alert(b instanceof Array); //a,b,c //true |
.sort( ) | 对数组的元素进行排序(按编码),按大小排序需要比较函数 | 新数组 | alert(a.sort(check)); function check(){ return a<b}//3,2,1 |