索引
const numbers=[5,6,13,0,1,2]
const double=numbers.map(function (number) {
return 2*number;
})
//1个参数时可带括号或者不带括号
const double1=numbers.map((number)=>{
return 2*number;
})
const double2=numbers.map(number=>{
return 2*number
})
//隐式返回
const double3=numbers.map((number)=>2*number);
//大于1个参数
const double4=numbers.map((number,i)=>`${i}:${number}`)
//无任何参数
const double5=numbers.map(()=>`hello`)
const greet=(name)=>{
console.log(`hello ${name}`)
}
greet("hk")
const Jelly={
name:‘Jelly‘,
hobbies:["coding","music",‘reading‘],
printHobbies:function(){
//console.log(this);//指向Jelly对象
this.hobbies.map(function(hobby){
//console.log(this) //这个函数独立调用时this指向window
console.log(`${this.name} loves ${hobby}`); //这里的this.name为空的
})
}
}
Jelly.printHobbies()
//传统修改
const Jelly1={
name:‘Jelly‘,
hobbies:["coding","music",‘reading‘],
printHobbies:function(){
const self=this;
this.hobbies.map(function(hobby){
console.log(`${self.name} loves ${hobby}`);
})
}
}
Jelly1.printHobbies();
//ES6里
const Jelly2={
name:‘Jelly‘,
hobbies:["coding","music",‘reading‘],
printHobbies:function(){
this.hobbies.map(hobby=>{
console.log(`${this.name} loves ${hobby}`);
})
}
}
Jelly2.printHobbies();
const Person=function (name,points) {
this.name=name
this.points=points;
}
const Person1=(name,points)=>{
this.name=name
this.points=points;
}
const p=new Person(‘hk‘,100)
//const p1=new Person1(‘hk1‘,90);//Uncaught TypeError: Person1 is not a constructor
Person.prototype.updatePoints=()=>{
console.log(this) //指向window
this.points++
}
const button=document.querySelector(".zoom")
button.addEventListener("click",function(){ //这里不该使用箭头函数
this.classList.add(‘roate‘);
setTimeout(()=>{ //这里需要继承上级的this所以用箭头函数
this.classList.remove(‘roate‘)
},2000)
})
const sum=function(){ //如果写成箭头函数,没有arguments对象报错
return Array.from(arguments).reduce(
(preSum,value)=>preSum+value,0
)
}
//array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
原文:https://www.cnblogs.com/HKUI/p/13112077.html