puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

The Array.prototype.map( ) in JavaScript #2

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

OK, so the Array.prototype.map( ) in JavaScript, pretty simple one, but today I was stucked by this for more than three hours.

We are already getting used to the most basic function of this Map( ) function of JS.

Basic Function

var array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2); // pass a function to map
console.log(map1);   // expected output: Array [2, 8, 18, 32]

Well, this is not the whole story yet, let's look deep into the definition on MDN

map

Here are the important points:

Sometimes when we use Map( ), it passes the second and third parameters automatically, and then creates problems.

Example with Two parameters

Using the example from the MDN website for better understanding

["1", "2", "3"].map(parseInt); //   result is [1, NaN, NaN];

first, let's take a look at the definition of parseInt from MDN

parseInt(string, radix);

string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored. radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful — this does not default to 10.

Therefore, parseInt( ) function needs two parameters. Combining with map( ) function, the array will pass the first two parameters to parseInt( ) function automatically.

// parseInt(string, radix) -> map(parseInt(value, index))
/*  first iteration (index is 0): */ parseInt("1", 0); // 1
/* second iteration (index is 1): */ parseInt("2", 1); // NaN
/*  third iteration (index is 2): */ parseInt("3", 2); // NaN

If we also consider about the Third Parameter, the array itself, the following example might be more clear.

Example with Three Parameters

const arr1 = ['1','2','3','4'];

function arrMap (para) {
  return para.map((str,index,arr)=>{
      return str;
  });
};

console.log(arrMap(arr1)); // ["1", "2", "3", "4"]

//return index
console.log(arrMap(arr1));  // [ 0, 1, 2, 3]

//return arr
console.log(arrMap(arr1));  // [Array[4], Array[4], Array[4], Array[4]]

The third parameter is not used very often, but the first two could be applied into projects and might bring some convenience.