-1
var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
  return x * 2;
  //doubles is now [2, 10, 20, 30]

I am following this above example, This is working for a constant 2, how can I mulitply the elements with variable this.price,

var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
   return x * this.price;

How can I make this works? this.price is a public variable.

Mukul Sharma
  • 176
  • 2
  • 5
  • 19

3 Answers3

1
var doubles = numbers.map(function(x) {
   return x * this.price; // "this" refers to the function it's inside
})

You can pass the external context inside the function using the ES6 fat arrow :

let doubles = numbers.map( x => x * this.price ) // "this" now refers to the parent's scope
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

var numbers = [1, 5, 10, 15];

var doubles = numbers.map(x => x * 5);

console.log(doubles);
l.g.karolos
  • 1,131
  • 1
  • 10
  • 25
-3

simply use the loop for,foreach or while.

var numbers = [1, 5, 10, 15];
for (index = 0; index < numbers .length; ++index) {
    //your multiplication code goes here
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Waseem Bashir
  • 638
  • 3
  • 10
  • 26