JS怎样精简这样的循环

JavaScript

如下代码,循环里除了判断的条件不一样,其它都是一样的。判断的条件里有可能会包含i,也有可能不含i。有没有办法精简它们??


// obj 这是一个json

loop1(){

    for(let i=0;i<obj.length;i++){

        if(i%2!==0){

            doSomethingA()

        } else {

            doSomethingB()

        }

    }

}

loop2(){

    for(let i=0;i<obj.length;i++){

        if(i%2!==0 && i!==0){

            doSomethingA()

        } else {

            doSomethingB()

        }

    }

}

loop3()。。。

loop4()。。。


慕森卡
浏览 406回答 4
4回答

青春有我

// obj = xxxxfunction loop (predicate) {&nbsp; &nbsp; for (let i = 0; i < obj.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (predicate(i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; doSomethingA()&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; doSomethingB()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}loop(i => i % 2 !== 0)loop(i => i % 2 !== 0 && i !== 0)

智慧大石

function loop (obj, fun) {&nbsp; for (let i = 0; i < obj.length; i++) {&nbsp; &nbsp; if (fun(i, obj)) {&nbsp; &nbsp; &nbsp; doSomethingA()&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; doSomethingB()&nbsp; &nbsp; }&nbsp; }}loop1 等价于 loop(obj, function(i) {return i % 2 !== 0})loop2 等价于 loop(obj, function(i) {return i % 2 !== 0 && i !== 0})

胡说叔叔

let loop = (fun) => {obj.forEach((v, k) => {if&nbsp;(fun)&nbsp;{}&nbsp;else&nbsp;{ }})}loop(fun)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript