一次移动到下一个迭代

我有一个名为 current 的变量,它存储数字 0 和长度为 4 的数组,我想迭代该数组,然后将其一次添加到当前变量一个,如果第一个变量没有传递到下一个变量,我怎样才能实现这一点请帮忙 !!!例如:


    /*2 0

      7 0

      11 0

      15 0*/


if not try the next one:


  /*2 1

    7 1

    11 1

    15 1*/

so on and so forth


let nums = [2,7,11,15]

let target = 18

let current = 0


nums.forEach(function(k,i){

let begin = current

if(nums[begin]+nums[i] === target){

  console.log(true)

}else{

begin++

}

console.log(nums[begin],nums[i])


})


心有法竹
浏览 90回答 2
2回答

暮色呼如

let nums&nbsp; &nbsp; = [2,7,11,15]&nbsp; , target&nbsp; = 18&nbsp; , flag=0&nbsp; , i, j&nbsp; ;for( i=0; i<nums.length-1; i++) {&nbsp; for( j=i+1; j<nums.length; j++) {&nbsp; &nbsp; if((nums[i]+nums[j])===target) {&nbsp; &nbsp; &nbsp; &nbsp; flag=1;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;}&nbsp; }&nbsp; if(flag) break;}console.log(nums[i],nums[j]);

慕哥9229398

那 ?let nums&nbsp; &nbsp; = [2,7,11,15]&nbsp; , target&nbsp; = 18&nbsp; , i, j, found = false&nbsp; ;for(i=0; i<nums.length-1; i++) {&nbsp; for( j=i+1; j<nums.length; j++) {&nbsp; &nbsp; found = (nums[i]+nums[j])===target&nbsp;&nbsp; &nbsp; if (found) break;&nbsp; }&nbsp; if (found) break;}if (found) console.log('values = ', nums[i],'+', nums[j], '=', target )else&nbsp; &nbsp; &nbsp; &nbsp;console.log('none' )您也可以这样做:let nums&nbsp; &nbsp; = [2,7,11,15]&nbsp; , target&nbsp; = 18&nbsp; , i=0, j=1, sum = nums[i] + nums[j]&nbsp; ;while (sum != target)&nbsp; {&nbsp; if (++j===nums.length )&nbsp; &nbsp; if (++i===(nums.length-1)) break&nbsp; &nbsp; else j=i+1&nbsp; sum = nums[i] + nums[j]&nbsp; }if (sum===target) console.log('values = ', nums[i],'+', nums[j], '=', target )else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('none' )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript