js中关于循环的那些API

作者: RichardBillion | 来源:发表于2017-03-26 16:26 被阅读723次

数组循环

针对数组,for循环完全OK,此处略过不表,只说一说为方便我们开发而那些内置的方法:

  • forEach

    就是for循环的简化,将每个值取出去做我们想做的事儿

    var arr=[1,2,3,4];
    arr.forEach(function(value,index){
        console.log(index+':'+value+'\n')
    })
    

    缺点是不能中断循环,没有break/continue方法。

    当然有时也可以使用some或者every方法在条件符合时退出循环,其使用方法和forEach无异,但他们常被用来确定数组的所有成员是否满足指定的测试。

    //some 方法在return值为true时终止遍历
    var arr=["java","lua","go","ruby"];
    arr.some(function(value,index){
        console.log(index+" : "+value)
        return value==="go"
    })
    //打印结果
    //0 : java
    //1 : lua
    //2 : go
    //true
    
    //every方法是当return返回值为false时退出循环
    arr.every(function(value,index){
        console.log(index+" : "+value)
        return value.length>3
    })
    //打印结果
    //0 : java
    //1 : lua
    //false
    
  • map

    对数组每个元素调用通用的映射方法。
    (对于下面的纯函数,我们就使用箭头函数了)

    let arr=[1,3,5,7]
    
    let newArr=arr.map(x=>0.5*x+3)
    
    
  • filter

    返回符合要求的元素

    //取出数组中大于10的数
    let arr=[1,5,17,23,9,12,10]
    let newArr=arr.filter(ele=>ele>10)
    //print result:
    //newArr=[17,23,12]
    
  • reduce方法

    reduce()接受一个方法作为回调,是一个数组逐项处理方法

    arr.reduce(callback[previousValue,currentValue],initialValue)
    

    其中initialValue作为第一次调用时传给previousValue的值

    previousValue 为上一次callback的返回值,所以适用于递归

    let arr=[1,2,3,4]
    let sum=arr.reduce((pre,cur)=>pre+cur ) 
    //10
    
    let multiplicative=arr.reduce((pre,cur)=>pre*cur)
    //24
    
    let max=arr.reduce((pre,cur)=>pre>cur?pre:cur)
    //4
    
    

对象循环

  • for - in

    for - in 是专门用来循环带有字符串key的可枚举对象的方法

    let obj = {a:1, b:2, c:3};
    for(let key in obj){
        console.log(key+" : "+obj[key])
    }
    //a : 1
    //b : 2
    //c : 3
    

ES6:for-of循环

这是ES6新提出的循环方法,可以用来循环除了适用于for-in的可枚举对象之外的任何东西。

  • 数组

    let arr=["java","lua","go","ruby"];
    for(let ele of arr){
        console.log(ele)
    }
    
  • 字符串

    let str="minelab"
    for(let char of str){
        console.log(char)
    }
    
  • Map

    let myMap = new Map([["a", 1], ["b", 2], ["c", 3]])
    for(let [key,value] of myMap){
        console.log(key+" : "+value)
    }
    //a : 1
    //b : 2
    //c : 3 
    
  • Set

    words=["ruby","java","ruby","java"]
    let uniqueWords=new Set(words)
    for(let word of uniqueWords){
        console.log(word)
    }
    //ruby
    //java
    

还有Dom Collection这样的类数组、生成器等等。

咦,说好的能够终止循环的功能呢?

let words=["ruby","java","ruby","java"]
for(let word of words){
    if (word=='java') {
        break
    }
    console.log(word)
}
//ruby

嗯,是可以终止,可是如果我想要 index 呢?

for(let word of words.keys()){
    console.log(word)
}
// 0 1 2 3

那我想同时得到 index 和 value 呢?

for(let [index,word] of words.entries()){
    if (word=='java') {
        break
    }
    console.log(index,word)
}
//0 "ruby"

注意 let [index, word] of不能丢掉中括号。


说了这么多关于数组的API,就再写个常见的应用案例吧

扁平化多维数组

//题目意思是有
var arr= [1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
//使其成为
[1, 3, 4, 5, 6, 0, 1, 5, 9, 2, 5, 1, 5, 5]

方法1:

//手动迭代
function unfold(arr) {
    var result=[];
    arr.forEach(function(item){
        if (Array.isArray(item)) {
            unfold(item)
        }else{
            result.push(item)
        }
    })
    return result
}

unfold(arr);

方法2:

//使用reduce方法实现递归
const flatten=arr=>arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?flatten(cur):cur),[])
//reduce 方法中给了初始值一个空数组,是为了能顺利执行concat方法
let result=flatten(arr)

方法3:

//使用toString,转化为字符串,然后可以直接使用split分割成扁平的字符串数组,最后再转化为整形数组
result=arr.toString().split(',').map(data=>+data)

相关文章

网友评论

    本文标题:js中关于循环的那些API

    本文链接:https://www.haomeiwen.com/subject/izjkottx.html