js里各种for的区别

js里各种for的区别

For/In 循环
实例

var array={fname:“Bill”,lname:“Gates”,age:56};

for in 针对json数组用这个

   for(let index in array) {  
        console.log(index,array[index]);  
    };  

index是fname、Iname、age

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

let iterable = [3, 5, 7];
iterable.foo = "hello";
 
for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", 
}
 
forEach //数组的时候用这个,json数组不行 //没有返回值
array.forEach(v=>{  
    console.log(v);  
});
array.forEach(function(v){  
    console.log(v);  
});

只往里写一个值的时候,这个值就是值

​ var array = [0222, 2221, 231312, 3, 4, 5]

​ array.forEach((item, index) => {

​ console.log(item, index);

​ });

这样写的时候,第一个是值,第二个是下标
在这里插入图片描述

第三个如果 有的话是当前正操作的数组

array.forEach((value, index, array) => { //value为遍历的当前元素,index为当前索引,array为正在操作的数组

​ //do something

​ console.log(value);

​ console.log(index);

​ console.log(array);

​ console.log(’------------------------------’);

​ }) //thisArg为执行回调时的this值

在ES6中,增加了一个for of循环,使用起来很简单

var array = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
for (let v of array) {
console.log(v);
};


   v在这里就是value了,

![<img src="C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20201212141159532.png" alt="image-20201212141159532" style="zoom:67%;" />](https://img-blog.csdnimg.cn/20201212144626268.png)


let myString = "helloabc"; 

   for(let char of myString ) { 

​    console.log(char ); 

   }

![在这里插入图片描述](https://img-blog.csdnimg.cn/20201212144617822.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RoZVdvcjFk,size_16,color_FFFFFF,t_70)

#### map和set

![在这里插入图片描述](https://img-blog.csdnimg.cn/20201212144553279.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RoZVdvcjFk,size_16,color_FFFFFF,t_70)


map可以有返回值	

var y = array1.map(function(value,index){

console.log(value);   //可遍历到所有数组元素

return value + 10

});
console.log(y); //[11, 12, 13, 14, 15] 返回一个新的数组


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值