JS Arrow Function

Arrow Function

使用 =>简化代码

=>省略function

 const sayHello = function(){
   console.log(`Hello`);
 }

 const sayHello = () => {
   console.log(`Hello`);
 }

单行代码无需使用{}

//one line function does not need braces
const sayHello =()=> console.log(`Hello`);

单行返回

//one line returns
const sayHello= ()=> `Hello`;  //return `Hello`
//same as above
const sayHello = function(){
  return `Hello`;
}

返回{}object时需要套上括号

//Return object
const sayHello= ()=> ({msg:'Hello'}); //把object放入括号——不然会被当做function的内容

函数传入单个参数无需括号

//Single param does not need parenthesis  //单参数不用括号
const sayHello=name=>console.log(`Hello ${name}`);

函数传入多个参数需要括号

//Multiple params need parenthesis
const sayHello=(firstName,lastName)=>console.log(`Hello ${firstName} ${lastName}`);

使用map对object中每个对象进行操作

const users =['Nathan','John','William'];

const nameLengths = users.map(function(name){ //map对对象的每个元素执行函数
  return name.length;
});

优化上述代码

//Shorter
const nameLengths = users.map((name)=>{ //map对对象的每个元素执行函数
  return name.length;
});

再优化

//Shortest
const nameLengths = users.map(name=>name.length);

优化Fetch API

document.getElementById('button1').addEventListener('click',getText);

document.getElementById('button2').addEventListener('click',getJson);

document.getElementById('button3').addEventListener('click',getExternal);
//get local text file data
function getText(){
  fetch('test.txt')
  .then(res=>res.text())
  .then(data=>{   //前面return的
    document.getElementById('output').innerHTML=data;
  })
  .catch(err =>console.log(err));
}


//get local json data
function getJson(){
  fetch('post.json')
  .then(res=> res.json())
  .then(data=>{   //前面return的
    let output="";
    data.forEach(post=>output+=`<li>${post.title}</li>`);
    document.getElementById('output').innerHTML=output;
    //document.getElementById('output').innerHTML=data;
  })
  .catch(err=>console.log(err));
}

//get from external API
function getExternal(){
  fetch('https://api.github.com/users')
  .then(res=>res.json())
  .then(data=>{   //前面return的
    console.log(data);
    let output="";
    data.forEach(user=>output+=`<li>${user.login}</li>`);
    document.getElementById('output').innerHTML=output;
    //document.getElementById('output').innerHTML=data;
  })
  .catch(err=>console.log(err));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值