Home > Back-end >  How do I multiply each member of an array by a variable scalar in javascript?
How do I multiply each member of an array by a variable scalar in javascript?

Time:07-06

I'm writing a code that multiply each item in array with a variable scalar ( 2**i)

a=[1, 2, 3, 4]
for (let i=0; i<a.length; i  ) {
    let output = // 
}
console.log(output)   // **output = [1*(2**0), 2*(2**1), 3(2**2), 4(2**3)]**

CodePudding user response:

You can use map same as :

const a = [1, 2, 3, 4]
const output = a.map((ele, index) => ele*(2**index))
console.log(output) // **output = [1*(2**0), 2*(2**1), 3(2**2), 4(2**3)]**

CodePudding user response:

Just create an array out of the for and push the values.

a = [1, 2, 3, 4];
output = [];
for (let i = 0; i < a.length; i  ) {
  output.push(a[i] * (2 ** i));
}
console.log(output) 

  • Related