JavaScript 的一些编码规范

1、不要对参数重新赋值
// bad
function f1(a) {
  a = 1;
  // ...
}

function f2(a) {
  if (!a) { a = 1; }
  // ...
}

// good
function f3(a) {
  const b = a || 1;
  // ...
}

function f4(a = 1) {
  // ...
}
2、不要使用一元递增递减运算符(++, --)

根据 eslint 文档,一元递增和递减语句受到自动分号插入的影响,并且可能会导致应用程序中的值递增或递减的静默错误。使用 num += 1 而不是 num++ 来改变你的值也更具表现力。禁止一元递增和递减语句也会阻止无意中预先递增/预递减值,从而减少程序出现意外行为。

// bad
let num = 1;
num++;
--num;

// good
let num = 1;
num += 1;
num -= 1;
3、使用 === 和 !== 而不是 == 和 !=
  • Objects => true
  • Undefined => false
  • Null => false
  • Booleans => the value of the boolean
  • Numbers
    +0, -0, or NaN => false
    其他 => true
  • Strings
    ‘’ => false
    其他 => true

当你通过 == 比较两个值时,其中一个值可能受到强制转换:强制 - 自动将值从一种类型转换为另一种类型。

  • 0 == “0” // true
    0 == [] // true
    “0” == [] // false
  • 0 === “0” // false
    0 === [] // false
    “0” === [] // false
4、类型检测

类型检测优先使用 typeof。对象类型检测使用 instanceof。null 或 undefined 的检测使用 == null。

// string
typeof variable === 'string'
// number
typeof variable === 'number'
// boolean
typeof variable === 'boolean'
// Function
typeof variable === 'function'
// Object
typeof variable === 'object'
// RegExp
variable instanceof RegExp
// Array
variable instanceof Array
// null
variable === null
// null or undefined
variable == null
// undefined
typeof variable === 'undefined'
5、函数有多个参数时使用 options objects 构建函数

当某个函数有两个及以上参数时,就应当考虑使用 options object 了。通常来说,在一个接收四个及以上参数的函数身上使用 options object 是一个好主意!如果一个函数目前只需要一个参数,但将来会添加更多的参数,那么建议从一开始就使用 option object 而不是之后重写/重构代码。options objects 可以明确的表明每个参数的作用。

// 默认参数
function myLog(
    options = {
        aaaLog: 'haha',
        bbbLog: true,
    }
) {
    if (options.aaaLog) {
        console.log(options.aaaLog);
    }
    if (options.bbbLog) {
        console.log(options.bbbLog);
    }
};
myLog();
myLog({
    aaaLog: 123,
    bbbLog: false,
});
// haha
// true
// 123

// 无默认参数
function myLog(options) {
    if (options.aaaLog) {
        console.log(options.aaaLog);
    }
    if (options.bbbLog) {
        console.log(options.bbbLog);
    }
};
myLog({
    aaaLog: 123,
    bbbLog: false,
});

更简洁的写法:

// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;
}

// good
function getFullName(obj) {
  const { firstName, lastName } = obj;
}

// best
function getFullName({ firstName, lastName }) {
	...
}

如果函数返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值。这样便于以后添加返回值,以及更改返回值的顺序。

// bad
function processInput(input) {
  return [left, right, top, bottom];
}

// good
function processInput(input) {
  return { left, right, top, bottom };
}

const { left, right } = processInput(input);

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值