es6的循环方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了es6的循环方法相关的知识,希望对你有一定的参考价值。

参考技术A 1、find()方法

2、forEach()方法

  let arr2 = []

         arr.forEach(function(item,index)

            if(item.price>1500)

                arr2.push(item)             

         )

         console.log(arr2)

  let arr2 = []

         arr.forEach(function(item,index)

             arr2.push(item.name)

         )

         console.log(arr2);

3、filter()方法

   过滤 price > 1500 

         es6循环的过滤方法 回调函数里面 return 一个条件

        会返回一个符合条件的新数组  对原数组不会造成改变

         let arr2 = arr.filter(function(item,index)

             return item.price>1500

         )

         console.log(arr2,arr)

4、map()方法

  map循环 

         map可以把数组里面某一项组合成一个新数组

        对原数组不会造成改变

         let arr2 = arr.map(function(item,index)

             console.log(item,index)

             return item.price

         )

         console.log(arr2,arr);

ES6 for...of循环

1、for of

const arr = [‘red‘, ‘green‘, ‘blue‘];

for(let v of arr) {
  console.log(v); // red green blue
}

for...of循环可以代替数组实例的forEach方法。

const arr = [‘red‘, ‘green‘, ‘blue‘];

arr.forEach(function (element, index) {
  console.log(element); // red green blue
  console.log(index);   // 0 1 2
});

JavaScript 原有的for...in循环,只能获得对象的键名,不能直接获取键值。ES6 提供for...of循环,允许遍历获得键值。

var arr = [‘a‘, ‘b‘, ‘c‘, ‘d‘];

for (let a in arr) {
  console.log(a); // 0 1 2 3
}

for (let a of arr) {
  console.log(a); // a b c d
}

上面代码表明,for...in循环读取键名,for...of循环读取键值。如果要通过for...of循环,获取数组的索引,可以借助数组实例的entries方法和keys方法.

 

以上是关于es6的循环方法的主要内容,如果未能解决你的问题,请参考以下文章

javascript(ES6):比“for循环”更有效的方法吗?

ES6的循环与可迭代对象示例详解

ES6 for...of循环

es6 非常实用的必备技能, 代替for循环,方法有很多哦

es6-15 Iterator 和 for of 循环

es6常用方法