JavaScript中的数组map()方法可以快速地对数组中的每个元素进行操作,并返回一个新的数组。它的使用方法是:array.map(function(currentValue, index, arr), thisValue),其中,function是一个回调函数,currentValue表示当前元素的值,index表示当前元素的索引值,arr表示当前元素所属的数组,thisValue表示回调函数执行时的this对象。
数组map()方法的作用是:对数组中的每个元素依次执行指定的回调函数,并返回一个新的数组,其中包含回调函数的返回值。例如,我们可以使用map()方法将一个数组中的每个元素都转换为它们的平方:
var arr = [1, 2, 3, 4, 5]; var result = arr.map(function(currentValue, index, arr) { return currentValue * currentValue; }); // result = [1, 4, 9, 16, 25]
我们还可以使用map()方法将一个数组中的每个元素都转换为它们的字符串形式:
var arr = [1, 2, 3, 4, 5]; var result = arr.map(function(currentValue, index, arr) { return currentValue.toString(); }); // result = ["1", "2", "3", "4", "5"]
我们还可以使用map()方法将一个数组中的每个元素都转换为它们的布尔值:
var arr = [1, 2, 3, 4, 5]; var result = arr.map(function(currentValue, index, arr) { return !!currentValue; }); // result = [true, true, true, true, true]
JavaScript中的数组map()方法可以快速地对数组中的每个元素进行操作,并返回一个新的数组。它的使用方法是:array.map(function(currentValue, index, arr), thisValue),其中,function是一个回调函数,currentValue表示当前元素的值,index表示当前元素的索引值,arr表示当前元素所属的数组,thisValue表示回调函数执行时的this对象。