js 各循环的区别

for in是ES5标准,遍历key. 
for of是ES6标准,遍历value. 2019拼多多提前批秋招就考了这两者区别

 for...in循环会遍历一个object所有的可枚举属性。

   for...of会遍历具有iterator接口的数据结构

原生具备 Iterator 接口的数据结构如下。

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • 函数的 arguments 对象
  • NodeList 对象

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
 
let iterable = [3, 5, 7];
iterable.foo = "hello";
 
for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
 
for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

var obj2 = [1,2,3,4]
for (key in obj2){
  console.log(key)
}
//ES5语法
for(value of obj2){
  console.log(value)
}
//特点:ES6新特性,遍历的是元素值,可遍历数组或对象

答案结果是
0
1
2
3



1
2
3
4

 

 

一、原生JS forEach()和map()遍历

共同点:

    1.都是循环遍历数组中的每一项。

    2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。

    3.匿名函数中的this都是指Window。

    4.只能遍历数组。

1.forEach()

   没有返回值。

arr[].forEach(function(value,index,array){

  //do something

})

  • 参数:value数组中的当前项, index当前项的索引, array原始数组;
  • 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
  • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;

var ary = [12,23,24,42,1];  

var res = ary.forEach(function (item,index,input) {  

input[index] = item*10;  

})  

console.log(res);//--> undefined;  

console.log(ary);//--> 通过数组索引改变了原数组;  [ 120, 230, 240, 420, 10 ]


2.map() 

有返回值,可以return 出来。

arr[].map(function(value,index,array){

  //do something

  return XXX

})

  • 参数:value数组中的当前项,index当前项的索引,array原始数组;
  • 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了)
  •  
  • var ary = [12,23,24,42,1];  
  • var res = ary.map(function (item,index,input) {  
  • return item*10;  
  • })  
  • console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
  • console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值