-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
  • 166
  • 2
  • 6
  • 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
  • 25,196
  • 9
  • 41
  • 59
0

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

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

console.log(doubles);
l.g.karolos
  • 1,103
  • 1
  • 10
  • 24
-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
  • 5,810
  • 10
  • 43
  • 111
Waseem Bashir
  • 628
  • 2
  • 9
  • 25