for in会循环原型链上的可枚举属性和遍历的方法

for in 循环

今天在做项目的时候踩到了一个坑,就是在使用for in循环列表的时候会遍历原型链上的可枚举的属性。话不多说上代码解释。

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

我们再来看看arr长啥样
arr

我们在原型属性上添加了一个result,而for in 循环也会把原型链上的可枚举的属性给遍历出来,所以这会造成一些我们不希望看到的结果。

所以当我们想要遍历一个对象希望用到for in循环,可以用console先打印出来看看是否适合用for in。JS遍历对象的方法有很多,如果for in不适合我们还可以用for of ,foreach, 普通的for循环等等。

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的一些循环的方式

  • for in
let arr = ['n', 'i', 'h', 'a', 'o']
for (let i in arr) {
  console.log(i)
}
// 0 1 2 3 4

返回的是数组的索引

  • 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 可以遍历对象,而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的区别在于map会返回一个新的数组,而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通过函数筛选并返回需要的值

  • some
var ages = [3, 10, 18, 20];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
    console.log(ages.some(checkAdult));
}
//true

some方法遍历数组,只要有一个对象满足函数给定的条件则返回true,否则返回false

  • every
var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
   console.log(ages.every(checkAdult));

some方法遍历数组,所有对象满足函数给定的条件则返回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 按照函数给定的条件进行累积,可以用来累加或者类乘等计算,第一个参数是上次运算结果(如果是第一遍历则是数组的第一项),第二个参数则是即将遍历的项(如果是第一次遍历则是第二个数组项),如果有第三个参数,则第三个参数是运算次数(也可以理解为第二个参数的索引,第一次遍历就是1,第二次遍历就是2,如此类推)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。