for in 循環(huán)
今天在做項(xiàng)目的時(shí)候踩到了一個(gè)坑,就是在使用for in循環(huán)列表的時(shí)候會(huì)遍歷原型鏈上的可枚舉的屬性。話不多說上代碼解釋。
let arr = ['hello', 'world', 'I', 'am', 'chen']
arr.__proto__.result = 'hello world, I am chen'
for (let i in arr) {
console.log(arr[i])
}
// hello
//world
//I
//am
//chen
//hello world,I am chen
我們?cè)賮砜纯碼rr長(zhǎng)啥樣 
我們?cè)谠蛯傩陨咸砑恿艘粋€(gè)result,而for in 循環(huán)也會(huì)把原型鏈上的可枚舉的屬性給遍歷出來,所以這會(huì)造成一些我們不希望看到的結(jié)果。
所以當(dāng)我們想要遍歷一個(gè)對(duì)象希望用到for in循環(huán),可以用console先打印出來看看是否適合用for in。JS遍歷對(duì)象的方法有很多,如果for in不適合我們還可以用for of ,foreach, 普通的for循環(huán)等等。
let arr = ['hello', 'world', 'I', 'am', 'chen']
arr.__proto__.result = 'hello world, I am chen'
for (let i of arr) {
console.log(arr[i])
}
// hello
//world
//I
//am
//chen
順便羅列一下JS的一些循環(huán)的方式
- for in
let arr = ['n', 'i', 'h', 'a', 'o']
for (let i in arr) {
console.log(i)
}
// 0 1 2 3 4
返回的是數(shù)組的索引
- for of
let arr = ['n', 'i', 'h', 'a', 'o']
for (let i of arr) {
console.log(i)
}
// n i h a o
返回的是值
ps: for of跟for in的不同之處除了返回值不一樣,for in 可以遍歷對(duì)象,而for of則不可以
let a = {
'demo': 'helloworld',
'test': 'testdemo'
}
for (let i in a) {
console.log(i)
}
//demo test
for (let i of a) {
console.log(i)
}
//Uncaught TypeError: a is not iterable
- foreach
let arr = ['n', 'i', 'h', 'a', 'o']
arr.forEach((item, index)=> {
console.log(item, index)
})
//n 0
//i 1
//h 2
//a 3
//o 4
- map
let arr = ['n', 'i', 'h', 'a', 'o']
arr.map((item, index)=> {
console.log(item, index)
})
//n 0
//i 1
//h 2
//a 3
//o 4
map 跟 foreach的區(qū)別在于map會(huì)返回一個(gè)新的數(shù)組,而foreach則沒有返回值。
- filter
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
console.log(ages.filter(checkAdult);)
}
// [32,33,40]
filter通過函數(shù)篩選并返回需要的值
- some
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
console.log(ages.some(checkAdult));
}
//true
some方法遍歷數(shù)組,只要有一個(gè)對(duì)象滿足函數(shù)給定的條件則返回true,否則返回false
- every
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
console.log(ages.every(checkAdult));
some方法遍歷數(shù)組,所有對(duì)象滿足函數(shù)給定的條件則返回true,否則返回false
- reduce
var numbers = [65, 44, 12, 4];
tt = numbers.reduce((total, item) => {
console.log(item, total)
return item + total
})
console.log(tt)
reduce 按照函數(shù)給定的條件進(jìn)行累積,可以用來累加或者類乘等計(jì)算,第一個(gè)參數(shù)是上次運(yùn)算結(jié)果(如果是第一遍歷則是數(shù)組的第一項(xiàng)),第二個(gè)參數(shù)則是即將遍歷的項(xiàng)(如果是第一次遍歷則是第二個(gè)數(shù)組項(xiàng)),如果有第三個(gè)參數(shù),則第三個(gè)參數(shù)是運(yùn)算次數(shù)(也可以理解為第二個(gè)參數(shù)的索引,第一次遍歷就是1,第二次遍歷就是2,如此類推)