定义和用法
array.map(function(currentValue,index,arr), thisValue)
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
参数说明
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
实例
(1)返回一个数组,数组中元素为原始数组的平方根:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
输出结果为:
2,3,4,5
(2)数组中的每个元素乘于输入框指定的值,并返回新数组:
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>
const channels = [
{ id: '1', channel_name: '漂流侠', channel_type: 1, onoff: 1 },
{ id: '2', channel_name: '好周转', channel_type: 1, onoff: 1 },
{ id: '3', channel_name: '临时花', channel_type: 1, onoff: 1 }
];
const channel_tabs = channels.map( item => {
return {
channel: item.channel_name
}
})
const channel_tabs1 = channels.map( item => item.channel_name)
/*
原数组channels不变
* $channel_tabs = [ {channel: '漂流侠'},{channel: '好周转'},{channel: '临时花'}]
$channel_tabs1 = [ '漂流侠', '好周转', '临时花']
* */
</script>