map
-
接受一个函数,这个函数接受三个参数:第一个参数是当前处理的元素,第二参数是当前处理元素的索引值,第三个参数是该数组本身
-
map不改变原数组但是会返回新数组
-
不能使用continue或者break跳出或中断循环
arr = [1,3,4]
let newarr=arr.map(i=>{
return i+=1;
console.log(i);
})
console.log(arr)// [1,3,4] 不会改变原数组
console.log(newarr)// [2,4,5] 返回新数组
forEach
- 接受一个函数,这个函数接受三个参数,第一个参数是元素,第二参数是元素的下标,第三个参数是数组本身,注意第一个参数是对原来数组中对应元素的拷贝
arr = [10,20,30,40,50]
arr.forEach((item,index,data)=>{
item = item + 1
})
//打印arr仍然没有变化
arr.forEach((item,index,data)=>{
data[index]=data[index]+1
})
//打印的arr才会变成[11,21,31,41,51]
- 没有返回值,对数组的操作会改变原数组
- 不能使用break中断循环,不能使用continue跳出循环中的一个迭代。但是
forEach结合条件判断throw Error实现break效果;使用return语句实现continue效果
const arr = [1, 2, 3, 4, 5];
// 使用return 实现continue效果
arr.forEach(function (item) {
if (item === 3) {
return;
}
console.log(item);
});
// result:
// 1
// 2
// 4
// 5
//条件判断加throw Error实现break效果
arr.forEach(function (item) {
if (item === 3) {
throw new Error('end')
}
console.log(item);
});
// result:
// 1
// 2
// Uncaught Error: end
for...in
循环的是对象的键名(key)或者数组、字符串的下标值。更适合遍历对象,当然也可以遍历数组,但是会存在一些问题:比如index索引为字符串型数字,不能直接进行几何运算
var arr = [1,2,3]
for (let index in arr) {
let res = index + 1
console.log(res)
}
//01 11 21
-
使用
for...in会遍历数组、对象所有的可枚举属性,包括原型如果不想遍历原型方法和属性的话,可以在循环内部判断一下,使用
hasOwnProperty()方法可以判断某属性是不是该对象的实例属性
var arr = [1,2,3]
Array.prototype.a = 123
for (let index in arr) {
let res = arr[index]
console.log(res)
}
//1 2 3 123
for(let index in arr) {
if(arr.hasOwnProperty(index)){
let res = arr[index]
console.log(res)
}
}
// 1 2 3
- 可以使用break、continue中止或者跳出循环
- 不能遍历Symbol属性
let as = Symbol('a')
let bs = Symbol('b')
let Obj = {
[as]:'as',
[bs]:'bs',
name:'Ben',
age:30
}
for(const key in Obj){
console.log(key)
}
//name
//age
for...of
-
在遍历数组的时候,
for...in遍历的是数组索引值,而且for...of遍历的是数组内的元素,不包括原型属性和索引 -
for...of适用遍历数组/字符串/map/set/arguments等拥有迭代器接口(iterator)的数据结构,但是不能遍历对象,因为没有对象迭代器接口,但如果想遍历对象的属性,你可以用for...in循环或用内建的Object.keys()方法
let objs = {
name: "vinc",
age: "18",
work: "it"
};
for (let v of Object.keys(objs)) {
console.log(v, objs[v]);
}
// 'name' 'vinc'
// 'age' '18'
// 'work' 'it'
- 不能遍历Symbol属性
let as = Symbol('a')
let bs = Symbol('b')
let Obj = {
[as]:'as',
[bs]:'bs',
name:'Ben',
age:30
}
for(const key of Object.keys(Obj)){
console.log(key)
}
//name
//age
some
在some方法中,return 返回的结果为true的话,会终止循环;return结果为false,表示跳过此次循环
//return结果为true
const arr = [1, 2, 3, 4, 5];
arr.some(function (item) {
console.log(item);
return item === 3;
});
// result:
// 1
// 2
// 3
//return结果为false
const arr = [1, 2, 3, 4, 5];
arr.some(function (item) {
if (item === 2) {
return;
}
console.log(item);
});
// result:
// 1
// 3
// 4
// 5
every
在every方法中,return 返回结果为false,会中断整个循环,return结果为true,理解为把当前符合条件的值记录下并会在循环结束后返回
//当内部return false时跳出整个循环
let list = [1, 2, 3, 4, 5];
list.every((value, index) => {
if(value > 3){
console.log(value)// 4
return false;
}else{
console.log(value)// 1 2 3
// 如果没有return true 的话,直接输出 1 后,跳出循环
return true
}
});