for...in/for...each/for...of的区别

简介: for...in/for...each/for...of的区别

for in

针对json数组使用

for in 会便利属性上的每个属性名称,

实例

let array={fname:“Bill”,lname:“Gates”,age:56};
   for(let index in array) {  
        console.log(index,array[index]);  
    };  
    //index是fname、Iname、age
    //array[index]为Bill、Gates、56
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
  console.log(i);  //  0, 1, 2, "foo", 
}

forEach

数组时使用,json数组不行 ,没有返回值

参数唯一的时候,就是值本身。

array.forEach(v=>{  
    console.log(v);  
});
array.forEach(function(v){  
    console.log(v);  
});

参数两个的时候,第一个为元素,第二个为下标

let array = [0222, 2221, 231312, 3, 4, 5]
 array.forEach((item, index) => {
 console.log(item, index);
 });

d6bb7edccfe2d1de0989d141b935ecf.png

第三个参数为当前正操作的数组

let array = [1, 221, 4312, 34, 64, 58]
array.forEach((value, index, array) => {
  console.log(value)    //value为遍历的当前元素
  console.log(index)  //index为当前索引
  console.log(array)  //array为正在操作的数组
  console.log('------------------------------------')
}) 
array . forEach (( value , index , array )=>{
// value 为遍历的当前元素, index 为当前索引, array 为正在操作的数组// do something console . log ( value )
 console . log ( index ) console . log ( array )
 console .1og('----
// thisArg 为执行回调时的 this 
(6)[1,221,4312,34,64,58]
221

for of

在ES6中增加的循环,使用方法简单

let array = ['a', 'b', 'c', 'd', 'e', 'f']
for (let v of array) {
  console.log(v);    //v在这里就是每个元素了,
};
>
 let array =[' a ',
 for ( let v of array ){
 console . log ( v );
' b '," c ", d ',' e "," f "
// v 在这里就是每个元素了,
};
 a 
 b 
 c 
 d 
 e 
 f
 undefined 
let myString = "helloabc"; 
for(let char of myString ) { 
    console.log(char); 
}



目录
相关文章
|
3天前
|
存储 缓存 移动开发
uinapp的setStorageSync和setStorage的区别
uinapp的setStorageSync和setStorage的区别
|
算法 Java Unix
C++基础语言之(二)C和C++的区别
C++基础语言之(二)C和C++的区别
|
12月前
bis和bic区别与实现
bis和bic区别与实现
102 0
|
JavaScript 小程序
bindtap和catchtap的区别?
在微信小程序中,bindtap 和 catchtap 都是用于绑定点击事件的属性,但它们在事件冒泡和事件捕获方面有所不同。
|
安全 C#
C#委托事件的区别
C#委托事件的区别
147 0
|
存储
逻辑移位与算术移位的区别
用一句简单的话来说就是:逻辑移位不需要考虑符号位,算术移位需要考虑符号位,我们都知道。数在计算机中都是以补码的形式来存储的,这才造成了逻辑移位和算术移位的的差别。
280 0
|
Java
While 与 do while 的区别
While 与 do while 的区别
66 0
!与~有什么区别
!与~有什么区别
86 0
||、&&、!的使用与区别
||、&&、!的使用与区别
116 0
|
安全
s=s+1,s+=1,++1,1++没有区别?
s=s+1,s+=1,++1,1++没有区别?