3

Array from method can be called with argument items and optional arguments mapfn and thisArg.

Array.from(items, mapfn, thisArg);

The following simple example demonstrate crating new Array using mapfn with multiply logic inside for each items value.

Array.from('123', (item, index) => item * 2); // [2, 4, 6];

What is the third argument? Please give me an example which will showing the case when i should use thisArg.

rossoneri
  • 443
  • 5
  • 17

2 Answers2

4

thisArg is Optional

  • Value to use as this when executing mapFn.

a = Array.from('2431', function(item){
  return item*this.multiply;
}, {multiply:2});
console.log(a)
// will return : [4, 8, 6, 2]
and it's identical to:

a = Array.from('2431', (item, index) => item * 2);
console.log(a)
// will return : [4, 8, 6, 2]

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
3

The third parameter is

Value to use as this when executing mapFn.

const x = Array.from('123', function(item) {
  console.log("THIS", this);
  return item * 2;
}, {
  test: "valueOfThis"
});

console.log("Result:", x);

ES6 version

const that = { test: "ValueOfThis" };
const x = Array.from('123', (item) => {
  console.log("THIS", that);
  return item * 2;
});

console.log("Result:", x);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • Can we use arrow function for `function(item)`? – Marfin. F Nov 24 '20 at 23:42
  • I tried it but it gives me *Undefined* value for `this.test` and it gives me `Object window` value for `this`. It is also applied for the arguments usage of arrow function. It is referred from here https://stackoverflow.com/questions/30935336/official-information-on-arguments-in-es6-arrow-functions. It does not work – Marfin. F Nov 25 '20 at 08:28
  • I thought it will be like this but does not work `const x = Array.from('123', (item) => { console.log("THIS", this); return item * 2; }, { test: "valueOfThis" });` – Marfin. F Nov 25 '20 at 16:02