js裡各種for的區別
阿新 • • 發佈:2020-12-19
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’]
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] 返回一個新的陣列