欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

数组&对象

程序员文章站 2022-09-04 17:12:35
一、遍历数组的几种方式 var arr = [1,2,3]; Array.prototype.test=function(){} arr.name='jq' 1、 for /* * index是number类型的,可以使用break,continue,return语句 * 可以遍历对象 */ for ......
一、遍历数组的几种方式
 
var arr = [1,2,3];
array.prototype.test=function(){} arr.name='jq'
 
1、 for 
/*
* index是number类型的,可以使用break,continue,return语句
* 可以遍历对象
*/
for (var index = 0, length = arr.length; index < length; index++) { console.log(index); // 0, 1, 2 console.log(arr[index]); // 1, 2, 3 }

 

2、 for in 遍历数组索引
/*
* 除了遍历数组元素外,还会遍历自身可枚举属性,以及原型链上属性
* 适用于普通对象,不适合数组遍历
* 可以使用break,continue,return语句
*/

for (var index in arr) {
    console.log(index); // 0, 1, 2, name, test
    console.log(arr[index]); // 1, 2, 3, jq, ƒ (){}
}

 

3、 for of 遍历数组元素值
/*
* 只遍历数组元素
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* 可以使用break,continue,return语句
*/

for (var item of arr) {
    console.log(item); // 1, 2, 3
}

 

4、 foreach 对数组每个元素执行一次提供的函数
/*
* 只遍历数组元素
* 参数:item 数组元素当前值,index 数组索引,array 数组本身
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* break,continue,return语句无效
*/

arr.foreach(function(item, index, array) {
    console.log(index); // 0, 1, 2
    console.log(item); // 1, 2, 3
})

 

5、 map 对数组元素处理,并返回一个新数组,原始数组不会被改变
/*
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* break,continue,return语句无效
* 参数:item 数组元素当前值,index 数组索引,array 数组本身
*/

arr.map(function(item, index, array) {
    console.log(index); // 0, 1, 2
    console.log(item); // 1, 2, 3
    return 0;
})

 

6、 reduce = map + filter
/*
* reduce 使用回调函数迭代地将数组简化为单一值
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* 参数:callback 和 初始值
* accumulator: 函数上一次调用的返回值
* item: item 数组元素当前值
*/

(1) 省略初始值,则accumulator为 arr[0], item为arr[1], index为1
arr.reduce(function(accumulator, item, index, array) {
    return accumulator + item; //求数组元素和
});

执行顺序:
1 + 2
3 + 3

(2) 有初始值,则accumulator为initvalue,item为arr[0], index为0
arr.reduce(function(accumulator, item, index, array) {
    return accumulator + item; //求数组元素和
}, 0);

执行顺序:
0 + 1
1 + 2
3 + 3

优点:减少数组迭代次数
 
(7) filter 返回符合指定条件的新数组
/*
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* item: item 当前数组元素
*/

arr.filter(function(item, index, array) {
    return (item > 1);
})


结果:[2, 3]

 

8、 find 返回符合指定条件的第一个元素/*
* 只适用于数组,set,map,类似数组对象,不适合普通对象对象
* item: item 当前数组元素
*/

arr.find(function(item, index, array) {
    return (item > 1);
})

结果:2

 

二、遍历对象的几种方式
1、for
2、for in
3、将对象转为数组object.keys