1

I have a for loop and inside I'd like to get a sequence like 1,-1,1,-1... (The loop does other things also so I don't want to alter the loop itself)

For now I have a solution like below, but there must be some more elegant way to do this I think :)

let plusMinus = [-1, 1]

for (let i = 0; i < 10; i++) {
  console.log(plusMinus[i % 2])
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Picard
  • 3,745
  • 3
  • 41
  • 50
  • please add, what means more elegant? – Nina Scholz Mar 14 '18 at 07:16
  • For me it's fewer lines, no redundant variables like `plusMinus` in my case. The best answer for me that I saw below was probably `console.log(Math.pow(-1, i))` but it is now gone. – Picard Mar 14 '18 at 08:31
  • 1
    that requires alwaays a mathematical operationb for a toggled value. maybe it is mor a question about do you want a value for an arbitrary value of `i`? then you could use `i % 2 || -1` without an array. – Nina Scholz Mar 14 '18 at 08:38
  • Thanks @NinaScholz this is even better than the `Math.pow` because it uses only simple operators - I knew there should be such simple solution but I couldn't figure it out! – Picard Mar 14 '18 at 09:05

2 Answers2

1
 let state = 1;
 for (let i = 0; i < 10; i++) 
    console.log(state = -state)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

Use Array.from :

var length = 5;
var sequence = Array.from(Array(length), (x, i) => i % 2 ? -1 : 1);
console.log(sequence);
Faly
  • 13,291
  • 2
  • 19
  • 37