简体   繁体   中英

fill in the values of an array using the array.map

I'm trying to understand this code that uses Array.map()

var char_set = Array.apply(null, Array(256)).map(Boolean.prototype.valueOf, false); 

The above code is creating an array with indexes from 0-255 and the each value is set to false

Could someone explain how this array is being created with this map method. The syntax of map method is

arr.map(callback[, thisArg])

In my case is thisArg set to false ?

Array.apply(null, Array(256)) : will create array of 256 elements with value undefined in all the elements

map(…) : is used to initialize all values to false

The first argument in map takes a callback function; Boolean.prototype.valueOf is a function that will act as a callback.

true.valueOf() returns true but it has to be invoked with thisArg.
|
---------- true is thisArg

false.valueOf() returns false but it has to be invoked with thisArg.
|
---------- false is thisArg

when map(Boolean.prototype.valueOf, false) is invoked for each element in an array it will pass false as this to Boolean.prototype.valueOf method. It is as good as invoking false.valueOf() hence it always returns false .

Thus map(Boolean.prototype.valueOf, false) is equivalent to:
map(function(item){ return false.valueOf() });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM