最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can I run two for loops in one statement in javascript? - Stack Overflow

programmeradmin5浏览0评论

Can I run two for loops in one statement in javascript? Would I do it like this?

for(initialize1,initialize2; condition1,condition2; incrementation1,incrementation2) 

Can I run two for loops in one statement in javascript? Would I do it like this?

for(initialize1,initialize2; condition1,condition2; incrementation1,incrementation2) 
Share Improve this question edited Oct 11, 2012 at 21:51 Anthony Mastrean 22.4k23 gold badges117 silver badges190 bronze badges asked Oct 11, 2012 at 21:44 samdonly1samdonly1 4383 gold badges5 silver badges12 bronze badges 2
  • 1 Try it for(var i = 0, j = 0; i <= 10 && j <= 10; i++, j++){ console.log(i + j) } – Kyle Commented Oct 11, 2012 at 21:50
  • TL;DR: Yes, in the initializer and loop (not the condition) sections, with mas. – Andrew Commented Feb 3, 2020 at 20:35
Add a ment  | 

3 Answers 3

Reset to default 6

Yes you can do a for loop like that, but you have one and just one condition for check. If you can make it check just a one condition for all of your variables for example an And (&&) conditional expression this will work fine, or if you just use the other variables for do something else it will work fine too.

Try it:

for(var i=j=k=0; j<9 && k<12;i++, j++, k++){
    console.log(i,j,k);      
    i = 12;
}

@samdonly1

Always you will have just one evaluation, but you can do something like this:

function evalFor(i, j, k){
   if (k == 9) return false;
   else if (j == 7) return false;
   else if (i == 12 && j == 6) return false;
   else return true;
}
for(var i=j=k=0; evalFor(i, j, k);i++, j++, k++){
    console.log(i,j,k);     
    i = 11;
}

In this case you can check your variables i, j, k in other function and decide if the loop stops or goes on.

Which one of these do you mean? This will execute one loop and wait for either condition1 or condition2 to fail:

for (initialize1, initialize2; condition1 && condition2; incrementation1, incrementation2)

This will execute one loop nested inside the other:

for (initialize1; condition1; incrementation1)
    for (initialize2; condition2; incrementation2)

I mean, the way I did something like this was basically trying to access a nested array in position [0,2],[1,1],[2,0] My solution was simple. ran a counter every time it looped

let matrix = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]
let leftDiag = []
let rightDiag = []
let counterJ =matrix.length-1
for(let i =0;i<matrix.length; i++){
  leftDiag.push(matrix[i][i])
  rightDiag.push(matrix[i][counterJ])
  console.log(i, counterJ)
  counterJ-=1
}
console.log(leftDiag)
console.log(rightDiag)

发布评论

评论列表(0)

  1. 暂无评论