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));
}
本文探讨了如何利用箭头函数简化JavaScript代码,包括省略function关键字、单行代码简化、返回对象的注意事项、参数处理以及在map和Fetch API中的应用。
5717

被折叠的 条评论
为什么被折叠?



