Home > database >  How do I write this JavaScript loop for if?
How do I write this JavaScript loop for if?

Time:10-26

if (item   600 === itemNew) {
  list.push(obj[i]);
} else {
  list.push({,
    Time: item
  });
  if (item   1200 !== itemNew) {
    list.push({
      Time: item   600
    });
    if (item   1800 !== itemNew) {
      list.push({
        Time: item   1200
      });
      if (item   2400 !== itemNew) {
        list.push({
          Time: item   1800
        });
        if (item   3000 !== itemNew) {
          list.push({
            Time: item   2400
          });
          if (item   3600 !== itemNew) {
            list.push({
              Time: item   3000
            });
            if (item   4200 !== itemNew) {
              list.push({
                Time: item   3600
              });
            }
          }
        }
      }
    }
  }
}

I want to check and get the distance of two numbers relative to the value of 600. There is a loop that has a condition and must be traversed. We check the previous value and if it is not the same as the next value, we add 600 to reach the condition

CodePudding user response:

You can do it using a normal for like this and creating an array with the times.

const times = [600, 1200, 1800, 2400, 3000, 3600, 4200];
const item = 5000;
const list = [];
const itemNew = 10000;
if (item   600 === itemNew) {
  list.push(obj[i]);
} else {
  list.push({
    Time: item
  });
  for(let i = 1; i < times.length;   i){
    if(item   times[i] !== itemNew){
      list.push({
        Time: item   times[i-1]
      });
    }
  }
}

console.log(list)

Or if you want it with a fixed interval you can do it having a maximum number of iterations and the multiplier like this:

const item = 5000;
const list = [];
const itemNew = 10000;
const MAX_ITER = 7;
const multiplier = 600;
if (item   600 === itemNew) {
  list.push(obj[i]);
} else {
  list.push({
    Time: item
  });
  for(let i = 2; i <= MAX_ITER;   i){
    if(item   multiplier * i !== itemNew){
      list.push({
        Time: item   multiplier * (i - 1)
      });
    }
  }
}

console.log(list)

CodePudding user response:

Check this:

const item = 1000;
const itemNew = 5000;

const length = (itemNew - item - (itemNew - item) % 600) / 600;
const list = Array(length).fill(0).map((_, i) => ({
  Time: item   (i   1) * 600
}));

console.log(list);

  • Related