JavaScript 学习笔记(四)

异常处理

高级语言通常都提供了更抽象的错误处理逻辑try … catch … finally,JavaScript也不例外。

try … catch … finally

使用try … catch … finally处理错误时,我们编写的代码如下:

1
2
3
4
5
6
7
8
9
10
11
var r1, r2, s = null;
try {
r1 = s.length; // 此处应产生错误
r2 = 100; // 该语句不会执行
} catch (e) {
console.log('出错了:' + e);
} finally {
console.log('finally');
}
console.log('r1 = ' + r1); // r1应为undefined
console.log('r2 = ' + r2); // r2应为undefined

错误类型

JavaScript有一个标准的Error对象表示错误,还有从Error派生的TypeErrorReferenceError等错误对象。我们在处理错误时,可以通过catch(e)捕获的变量e访问错误对象:

1
2
3
4
5
6
7
8
9
10
11
try {
...
} catch (e) {
if (e instanceof TypeError) {
alert('Type error!');
} else if (e instanceof Error) {
alert(e.message);
} else {
alert('Error: ' + e);
}
}

使用变量e是一个习惯用法,也可以以其他变量名命名,如catch(ex)

抛出错误

程序也可以主动抛出一个错误,让执行流程直接跳转到catch块。抛出错误使用throw语句。

1
2
3
4
5
6
7
8
9
10
11
12
13
var r, n, s;
try {
s = prompt('请输入一个数字');
n = parseInt(s);
if (isNaN(n)) {
throw new Error('输入错误');
}
// 计算平方:
r = n * n;
console.log(n + ' * ' + n + ' = ' + r);
} catch (e) {
console.log('出错了:' + e);
}

实际上,JavaScript允许抛出任意对象,包括数字、字符串。但是,最好还是抛出一个Error对象。

最后,当我们用catch捕获错误时,一定要编写错误处理语句:

1
2
3
4
5
6
7
var n = 0, s;
try {
n = s.length;
} catch (e) {
console.log(e);
}
console.log(n);

哪怕仅仅把错误打印出来,也不要什么也不干:

1
2
3
4
5
6
var n = 0, s;
try {
n = s.length;
} catch (e) {
}
console.log(n);

因为catch到错误却什么都不执行,就不知道程序执行过程中到底有没有发生错误。

catch 命令的参数省略

JavaScript 语言的try...catch结构,以前明确要求catch命令后面必须跟参数,接受try代码块抛出的错误对象。

1
2
3
4
5
try {
// ...
} catch (err) {
// 处理错误
}

上面代码中,catch命令后面带有参数err

很多时候,catch代码块可能用不到这个参数。但是,为了保证语法正确,还是必须写。ES2019 做出了改变,允许catch语句省略参数。

1
2
3
4
5
try {
// ...
} catch {
// ...
}

编程风格

块级作用域

let代替var

ES6 提出了两个新的声明变量的命令:letconst。其中,let完全可以取代var,因为两者语义相同,而且let没有副作用。

全局常量和线程安全

letconst之间,建议优先使用const,尤其是在全局环境,不应该设置变量,只应设置常量。

字符串

静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号。

1
2
3
4
5
6
7
8
9
10
// bad
const a = "foobar";
const b = 'foo' + a + 'bar';

// acceptable
const c = `foobar`;

// good
const a = 'foobar';
const b = `foo${a}bar`;

解构赋值

使用数组成员对变量赋值时,优先使用解构赋值。

1
2
3
4
5
6
7
8
const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;

函数的参数如果是对象的成员,优先使用解构赋值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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 }) {
}

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

1
2
3
4
5
6
7
8
9
10
11
// bad
function processInput(input) {
return [left, right, top, bottom];
}

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

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

对象

单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
const a = { k1: v1, k2: v2, };
const b = {
k1: v1,
k2: v2
};

// good
const a = { k1: v1, k2: v2 };
const b = {
k1: v1,
k2: v2,
};

对象尽量静态化,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用Object.assign方法。

1
2
3
4
5
6
7
8
9
10
11
// bad
const a = {};
a.x = 3;

// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });

// good
const a = { x: null };
a.x = 3;

如果对象的属性名是动态的,可以在创造对象的时候,使用属性表达式定义。

1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};

对象的属性和方法,尽量采用简洁表达法,这样易于描述和书写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var ref = 'some value';

// bad
const atom = {
ref: ref,

value: 1,

addValue: function (value) {
return atom.value + value;
},
};

// good
const atom = {
ref,

value: 1,

addValue(value) {
return atom.value + value;
},
};

数组

使用扩展运算符(…)拷贝数组。

1
2
3
4
5
6
7
8
9
10
11
// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];

使用 Array.from 方法,将类似数组的对象转为数组。

1
2
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);

函数

那些使用匿名函数当作参数的场合,尽量用箭头函数代替。因为这样更简洁,而且绑定了 this。

1
2
3
4
5
6
7
8
9
10
11
12
// bad
[1, 2, 3].map(function (x) {
return x * x;
});

// good
[1, 2, 3].map((x) => {
return x * x;
});

// best
[1, 2, 3].map(x => x * x);

所有配置项都应该集中在一个对象,放在最后一个参数,布尔值不可以直接作为参数。

1
2
3
4
5
6
7
// bad
function divide(a, b, option = false ) {
}

// good
function divide(a, b, { option = false } = {}) {
}

不要在函数体内使用 arguments 变量,使用 rest 运算符(…)代替。因为 rest 运算符显式表明你想要获取参数,而且 arguments 是一个类似数组的对象,而 rest 运算符可以提供一个真正的数组。

1
2
3
4
5
6
7
8
9
10
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}

// good
function concatenateAll(...args) {
return args.join('');
}

使用默认值语法设置函数参数的默认值。

1
2
3
4
5
6
7
8
9
// bad
function handleThings(opts) {
opts = opts || {};
}

// good
function handleThings(opts = {}) {
// ...
}

Map结构

注意区分 Object 和 Map,只有模拟现实世界的实体对象时,才使用 Object。如果只是需要key: value的数据结构,使用 Map 结构。因为 Map 有内建的遍历机制。

1
2
3
4
5
6
7
8
9
10
11
12
13
let map = new Map(arr);

for (let key of map.keys()) {
console.log(key);
}

for (let value of map.values()) {
console.log(value);
}

for (let item of map.entries()) {
console.log(item[0], item[1]);
}

模块

Module 语法是 JavaScript 模块的标准写法,使用import取代require

1
2
3
4
5
6
7
// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;

// good
import { func1, func2 } from 'moduleA';

使用export取代module.exports

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// commonJS的写法
var React = require('react');

var Breadcrumbs = React.createClass({
render() {
return <nav />;
}
});

module.exports = Breadcrumbs;

// ES6的写法
import React from 'react';

class Breadcrumbs extends React.Component {
render() {
return <nav />;
}
};

export default Breadcrumbs;

如果模块只有一个输出值,就使用export default,如果模块有多个输出值,就不使用export defaultexport default与普通的export不要同时使用。

文章作者: Jie
文章链接: https://blog.zhangjie.me/2021/02/02/JavaScript-Learning-Notes-four/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 JieのBlog