JavaScript ,Array map 方法
map 方法 (Array) (JavaScript)
对数组的每个元素调用定义的回调函数并返回包含结果的数组。
array1.map(callbackfn[, thisArg])
参数
// Define the callback function. function AreaOfCircle(radius) { var area = Math.PI * (radius * radius); return area.toFixed(0); } // Create an array. var radii = [10, 20, 30]; // Get the areas from the radii. var areas = radii.map(AreaOfCircle); document.write(areas); // Output: // 314,1257,2827
this 关键字可引用的对象。
// Define an object that contains a divisor property and // a remainder function. var obj = { divisor: 10, remainder: function (value) { return value % this.divisor; } } // Create an array. var numbers = [6, 12, 25, 30]; // Get the remainders. // The obj argument specifies the this value in the callback function. var result = numbers.map(obj.remainder, obj); document.write(result); // Output: // 6,2,5,0
在下面的示例中,内置 JavaScript 方法用作回调函数。
// Apply Math.sqrt(value) to each element in an array. var numbers = [9, 16]; var result = numbers.map(Math.sqrt); document.write(result); // Output: 3,4
下面的示例阐释了这一点。
// Define the callback function. function threeChars(value, index, str) { // Create a string that contains the previous, current, // and next character. return str.substring(index - 1, index + 2); } // Create a string. var word = "Thursday"; // Apply the map method to the string. // Each array element in the result contains a string that // has the previous, current, and next character. // The commented out statement shows an alternative syntax. var result = [].map.call(word, threeChars); // var result = Array.prototype.map.call(word, threeChars); document.write(result); // Output: // Th,Thu,hur,urs,rsd,sda,day,ay
要求
版本信息。
在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式、Internet Explorer 8 标准模式。