笔记来自:https://github.com/airbnb/javascript
1.使用const,避免使用var来确保引用不被重写分配
// bad
var a = 1 ;
var b = 2 ;
//好
const a = 1 ;
const b = 2 ;
使用属性值速记
<script>
const spiderMan = "spiderMan";
let person = {
spiderMan //spiderMan:"spiderMan"
}
console.log(person.spiderMan);
</script>
判断对象是否具有属性–可以避免空对象
<script>
let person = {
name:'zs',
age:'18'
}
const hasProp = Object.prototype.hasOwnProperty;
console.log(hasProp.call(person,'name'))
</script>
2.使用...
克隆对象来替代Object.assign
浅表复制对象
<script>
let person = {
name:'zs',
age:'18'
};
let zsf = {...person,sex:'男'};
console.log(zsf);//{name: "zs", age: "18", sex: "男"}
</script>
3.使用数组跨度来复制数组
<script>
let item = [1,2,3];
let itemCopy = [...item];
console.log(itemCopy);//[1, 2, 3]
</script>
4.将可迭代对象转化为数组,使用...
而不是array.form
<script>
let spanEle = document.querySelectorAll("span");
let spanEle_array = [...spanEle];
console.log(spanEle_array)
</script>
5.使用Array.from
而不是扩展...
来映射可迭代对象,因为它避免了创建中间数组
const arrLike = { 0:'foo' , 1:'bar' , 2:'baz' , length:3 } ;
//好
const arr = Array.from(arrLike);
console.log(arr);
6.避免使用+拼接
<script>
const a = 'zs';
const b = 'ls';
const c = `${a},${b}`;
console.log(c)//zs,ls
</script>
7.使用对象解构
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}
// best
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}
8.使用数组解构
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
9.对于立即调用的函数应该使用()
(
function () {
console.log('Welcome to the Internet. Please follow me.');
}()
);
10.不应该在if、while中声明函数
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
11.使用...
来调用可变参数函数
<script>
let date = new Date(...[2010,2,23,23,12,23]);
console.log(date);//Tue Mar 23 2010 23:12:23 GMT+0800 (中国标准时间)
</script>
12.使用箭头函数来替换匿名函数
// bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
13.使用箭头函数处理回调
<script>
function foo(callback){
const val = callback();
if(val===true){
console.log("do...")
}
}
foo(() => true);
</script>
14.使用WeakMap创建隐式私有变量,WeakMap 的 key 只能是 Object
类型。 原始数据类型 是不能作为 key 的
<script>
const person = {};
const firstNames = new WeakMap();
firstNames.set(person, 'Panda');
console.log(firstNames.get(person)); //Panda
</script>