下面是一个例子 数组映射() 方法
null
例子:
JavaScript
<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [14, 10, 11, 00]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func(); </script> |
输出:
3.7416573867739413,3.1622776601683795,3.3166247903554,0
这个 arr.map() 方法为每个数组元素创建一个新数组,其中包含调用函数的结果。此函数按顺序为给定数组的每个元素调用参数函数一次。 语法:
array.map(callback(element, index, arr), thisArg)
参数: 该方法接受上述五个参数,如下所述:
- 回拨: 此参数保存要为数组的每个元素调用的函数。
- 要素: 该参数保存当前正在处理的元素的值。
- 索引: 此参数是可选的,它保存数组中从0开始的currentValue元素的索引。
- arr: 此参数是可选的,它保存在哪个数组上的完整数组。每个人都被称为。
- thisArg: 此参数是可选的,它保存要传递的上下文,以便在执行回调函数时使用。如果传递了上下文,则每次调用回调函数时都会像这样使用它,否则默认使用undefined。
返回值: 此方法返回使用 arg_函数 使用原始数组中的值。此函数不会修改在其上实现此函数的原始数组。 下面的例子说明了 arr.map() JavaScript中的方法:
例1: 在本例中,方法 地图() 生成一个数组,其中包含原始数组中的数字除以2得到的数字。
var arr = [2, 56, 78, 34, 65];var new_arr = arr.map(function(num) { return num / 2;});print(new_arr);
输出:
[1, 28, 39, 17, 32.5]
例2: 在本例中,方法 地图() 生成一个数组,其中包含原始数组中数字的平方根。
var arr = [10, 64, 121, 23];var new_arr = arr.map(Math.sqrt);print(new_arr);
输出:
[3.1622776601683795, 8, 11, 4.795831523312719]
下面提供了上述功能的代码: 项目1:
JavaScript
<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [2, 56, 78, 34, 65]; // new mapped array var new_arr = arr.map( function (num) { return num / 2; }); document.write(new_arr); } func(); </script> |
输出:
1, 28, 39, 17, 32.5
项目2:
JavaScript
<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [10, 64, 121, 23]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func(); </script> |
输出:
3.1622776601683795, 8, 11, 4.795831523312719
支持的浏览器: JavaScript支持的浏览器 数组映射() 方法如下:
- 谷歌Chrome 1及以上版本
- 微软Edge 12及以上
- Mozilla Firefox 1.5及以上版本
- Safari 3及以上
- Opera 9.5及以上
Polyfill
Polyfills是用来代替任何不支持旧浏览器的函数的代码。
假设一个旧浏览器不具备最新的ES功能,那么你的代码将在该浏览器中中断。
这里我们创建一个数组的多边形填充。原型map()函数。步骤如下。
步骤:
- 检查浏览器是否支持map()函数。
- 现在创建一个函数表达式并将其分配到数组中。原型map和函数接受一个参数。
- 创建一个空数组。
- 迭代 这 使用 因为 环(这里的值是调用map函数的数组)
- 现在对每个迭代的值使用回调函数,并将其推入该数组(您创建的数组为空)
- 返回数组。
实施:
Javascript
// Check if the map function is supported by the browser or not if (!Array.prototype.map){ Array.prototype.map = function (callback){ // create an empty array let newArr = []; // Iterate the value of this // Here the value of this is the array by // which you called the map function for (let item of this ){ // Apply the callback function at every iteration // and push it into the newArr array newArr.push(callback(item)); } // return the newArr return newArr; } } let a = [ 1, 2, 3, 4, 5, 6] a.map((item)=>{ console.log(item) }) // This code is contributed by _saurabh_jaiswal |
输出:
123456
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END