添加到数字后,如何将数字循环回到开头?

时间:2018-03-27 02:24:09

标签: javascript loops for-loop

我要做的是为数组中的每个值添加一个数字,但是如果该值大于78但小于90,我希望它在通过数字90后循环回到65.含义如果我把10加到85,它会给我70.

这是我的目标。我只是想不出if语句之后要放什么。

emptyArr = [83, 69, 82, 82] 

function addingNum(x) {
 for(var k=0 ;  k < emptyArr.length ; k++){
  if (emptyArr[k] >= 78 && emptyArr[k] <= 90  ){



  }
  else {
      emptyArr[k] += 13;   
    }
}

 return emptyArr;
}

3 个答案:

答案 0 :(得分:2)

只需添加以下内容:

emptyArr[k] += 10;
if(emptyArr[k] >= 90) emptyArr[k] = 65 + emptyArr[k] - 90;

答案 1 :(得分:1)

怎么样:

emptyArr[k] = 65 + ((emptyArr[k] + x) % 90)

x要添加的号码。

演示:

&#13;
&#13;
emptyArr = [85, 83, 69, 82, 82, 90, 91]

function addingNum(x) {
  for (var k = 0; k < emptyArr.length; k++) {
    if (emptyArr[k] >= 78 && emptyArr[k] <= 90) {

      emptyArr[k] = 65 + ((emptyArr[k] + x) % 90)

    } else {
      emptyArr[k] += x;
    }
  }
  return emptyArr;
}

console.log(addingNum(10));
&#13;
&#13;
&#13;

如果您希望将其保持在65到90之间,无论x(已添加的值)是什么,请在%中使用x,例如:

emptyArr[k] = 65 + ((emptyArr[k] + (x % 25)) % 90)

演示:

&#13;
&#13;
emptyArr = [85, 83, 69, 82, 82, 90, 91]

function addingNum(x) {
  for (var k = 0; k < emptyArr.length; k++) {
    if (emptyArr[k] >= 78 && emptyArr[k] <= 90) {

      emptyArr[k] = 65 + ((emptyArr[k] + (x % 25)) % 90)

    } else {
      emptyArr[k] += x;
    }
  }
  return emptyArr;
}

console.log(addingNum(35));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以将差异添加到下限:

let arr = [83, 69, 82, 82]
console.log(addingNum([...arr], 10))

function addingNum(arr, x) {
  let maxNum = 90,
    minNum = 78
    
  for (var k = 0, n = arr.length; k < n; k++) {
    if (arr[k] >= minNum && arr[k] <= maxNum) {
      let newNum = arr[k] + x
      let difference = newNum - maxNum
      if (difference > 0)
        arr[k] = minNum + difference
    } else {
      arr[k] += 13
    }
  }

  return arr
}