JavaScript Array map() 方法
返回一个数组,数组中元素为原始数组的平方根:
<p>点击按钮获取数组元素的平方根。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
</script>
定义和用法
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
浏览器支持
表格中的数字表示支持该方法的第一个浏览器的版本号。
| 方法 | |||||
|---|---|---|---|---|---|
| map() | Yes | 9 | 1.5 | Yes | Yes |
语法
array.map(function(currentValue, index, arr), thisValue)
参数说明
| 参数 | 描述 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
|
||||||||
| thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined" |
技术细节
| 返回值: | 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。 |
|---|---|
| JavaScript 版本: | 1.6 |
更多实例
数组中的每个元素乘于输入框指定的值,并返回新数组:
<p>点击按钮将数组中的每个元素乘于输入框指定的值,并返回新数组。</p>
<p>最小年龄: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="myFunction()">点我</button>
<p>新数组: <span id="demo"></span></p>
<script>
var numbers = [65, 44, 12, 4];
function multiplyArrayElement(num) {
return num * document.getElementById("multiplyWith").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}
</script>
JavaScript Array 对象
JavaScript Array 对象