Map(),It is one of the array method in JavaScript released in the version of ECMA 3.
- It creates a new array with the results of calling a function for every values in the array.But it does not change the original array value and doesn't execute the function if array has no values.
- Actually map() is one of my favourite method in JavaScript,because it's really shrinks the code.Without map we have to proceed with for() or while().But map has some pros to overcome for() and while().
- so it's one of the good practices to use map() in large seized JavaScript application which has deal with manipulation of huge data from server.
Let's go to some example
- Create an HTML file.
- Within script create one array with values
var number=[10,20,30,40,50]; - Here's the syntax of map()
array.map(function(value,index,array),thisValue);
value: current value of the array-(required ).
index :returns index of the array-(optional).
array:returns the array of an element-(optional).
document.write(numbers.map(Math.sqrt));
Result:
2,3,4,5
Example 2:
numbers.map(function(item){
document.write(item+" , ")
});
Result:
4 , 9 , 16 , 25
Example 3:
var test=function(item,index,array){
console.log(item);
console.log(index);
console.log(array);
return index;
}
document.write(numbers.map(test));
Result:
in document
0,1,2,3
in console we got every element of array,index of that value and the whole array.
*And the second parameter of map () is thisValue is optional.
in document
0,1,2,3
in console we got every element of array,index of that value and the whole array.
*And the second parameter of map () is thisValue is optional.
Comments
Post a Comment