请教一个JavaScript函数的写法。

根据给出的数字生成相应的循环。如给出2,则生成2重循环,3则3重循环

如给出3,则


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

        for (let j = 0; j < arr.length; j++) {

            for (let k = 0; k < arr.length; k++) {

                

                }

            }

        }

 }


达令说
浏览 259回答 2
2回答

GCT1015

递归f(arr, 3, [])function f(arr,k,temp){&nbsp; &nbsp; if(k<=0){&nbsp; &nbsp; &nbsp; &nbsp; let sum = 0&nbsp; &nbsp; &nbsp; &nbsp; let r =[]&nbsp; &nbsp; &nbsp; &nbsp; for(let i = 0; i < temp.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += temp[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r.push(temp[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (sum&nbsp; === hz) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push(r)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; for (let i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; temp.push(arr[i])&nbsp; &nbsp; &nbsp; &nbsp; f(arr, k-1, temp)&nbsp; &nbsp; &nbsp; &nbsp; temp.splice(temp.length-1, 1)&nbsp; &nbsp; }}

婷婷同学_

這種需求一般都儘可能通過遞歸來解決的, 讓n作爲參數然後n = 0時跳出遞歸就行了. 強行要loop解決估計要一些奇技淫巧了.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript