<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>扩展运算符练习</title>
</head>
<body>
<script>
/*
现在在classGrade数组里面给每个值后面都加个班字
*/
const classGrade=['1313','1611'];
function addWord(word){
return [...word].map(letter=>`${letter}班`)
}
console.log(addWord(classGrade));//(2) ["1313班", "1611班"]
</script>
</body>
</html>
map说明(ES5):
起到一个映射的作用;
返回一个新的数组;
有两个参数:
第一个参数是:callback回调函数
callback回调函数里面的第一个参数是:
ele代表着正在处理的元素
callback回调函数里面的第二个参数是:
index代表着数组的索引值
callback回调函数里面的第三个参数是:
self代表着数组本身
第二个参数是:thisArg(可选)
代表着this默认指向window
const arr = [
{ name: '张三', age: 21 },
{ name: '李四', age: 22 },
{ name: '王五', age: 23 },
];
let obj = {naem: 'xyz'}
const newMap = arr.map(function(ele, index, self){
console.log(this)
return ele.age + 10
}, obj)
console.log(newMap)
result:
通过源码实现map方法:
//通过源码实现map方法
const arr = [
{ name: '张三', age: 21 },
{ name: '李四', age: 22 },
{ name: '王五', age: 23 },
];
Array.prototype.myMap = function (func) {
let arr = [];
let _this = arguments[1] || window;
for (let i = 0; i < this.length; i++) {
arr.push(func.apply(_this, [this[i], i, this]))
// arr.push(func.call(_this, this[i], i, this)
}
return arr
}
let obj = {
naem: 'xyz'
}
let newMap = arr.myMap(function (ele, index, self) {
console.log(this)
return ele.age + 21
})
console.log(newMap)
result: