给 JavaScript 初学者的提示和技巧
参考
对象
数组
概括
在本文中,我将分享一组 JavaScript 技巧、窍门和最佳实践,所有 JavaScript 开发人员都应该了解,无论他们使用什么浏览器/引擎或 SSJS(服务器端 JavaScript)解释器。
涵盖的主题包括:-
1. 引用,
2. 对象,
3. 数组
参考
- 1.1
const
用于所有参考;避免使用var
。
为什么?这确保你无法重新分配引用,否则可能会导致错误和难以理解的代码。
// bad way to write
var a = 1;
var b = 2;
// this is the good way to write avoid using var
const a = 1;
const b = 2;
- 1.2 如果必须重新分配引用,请使用
let
而不是var
。
为什么?
let
是块作用域,而不是像函数作用域var
。
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
- 1.3 请注意
let
和都是块作用域const
的。
// const and let only exist in the blocks they are defined in.
{
let a = 1;
const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
对象
- 2.1 使用文字语法来创建对象。
// bad
const item = new Object();
// good
const item = {};
- 2.2 创建具有动态属性名称的对象时,使用计算属性名称。
为什么?因为它们允许你在一处定义对象的所有属性。
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'Tony Stark',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'Tony Stark',
[getKey('enabled')]: true,
};
- 2.3 使用对象方法简写。
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
- 2.4 使用属性值简写。
为什么?因为它更简短,描述性更强。
const tonyStark = 'Tony Stark';
// bad
const obj = {
tonyStark: tonyStark,
};
// good
const obj = {
tonyStark,
};
- 2.5 在对象声明的开头对简写属性进行分组。
为何?因为使用简写更容易分辨哪些属性。
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
- 2.6 仅引用无效标识符的属性。
为什么?总的来说,我们认为它更容易阅读。它改进了语法高亮,也更容易被许多 JS 引擎优化。
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
- 2.7 不要
Object.prototype
直接调用方法,例如hasOwnProperty
、propertyIsEnumerable
和isPrototypeOf
。
为什么?这些方法可能被相关对象的属性所掩盖——考虑一下
{ hasOwnProperty: false }
——或者,该对象可能是一个空对象(Object.create(null))
。
// bad
console.log(object.hasOwnProperty(key));
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
- 2.8 对于浅复制对象,优先使用对象展开运算符,而非Object.assign。使用对象剩余运算符可以获取省略某些属性的新对象。
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
delete copy.a; // so does this
// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
数组
- 3.1 使用文字语法创建数组。
// bad
const items = new Array();
// good
const items = [];
- 3.2 使用Array#Push而不是直接赋值来向数组添加项目。
const someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
- 3.3 使用数组扩展
...
来复制数组。
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
- 3.4 要将可迭代对象转换为数组,请使用 spreads
...
而不是Array.from。
const foo = document.querySelectorAll('.foo');
// good
const nodes = Array.from(foo);
// best
const nodes = [...foo];
- 3.5 使用Array.from将类数组对象转换为数组。
const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };
// bad
const arr = Array.prototype.slice.call(arrLike);
// good
const arr = Array.from(arrLike);
- 3.6 使用Array.from而不是 spread
...
来映射可迭代对象,因为它避免创建中间数组。
// bad
const baz = [...foo].map(bar);
// good
const baz = Array.from(foo, bar);
- 3.7 在数组方法回调中使用 return 语句。如果函数体只包含一个返回无副作用表达式的语句,则可以省略 return 语句。
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map((x) => x + 1);
// bad - no returned value means `acc` becomes undefined after the first iteration
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
const flatten = acc.concat(item);
});
// good
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
const flatten = acc.concat(item);
return flatten;
});
// bad
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
} else {
return false;
}
});
// good
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
}
return false;
});
- 3.8 如果数组有多行,则在打开数组括号之后和关闭数组括号之前使用换行符。
// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];
概括
好了,以上就是一些实用的 JavaScript 技巧和窍门。希望你学到了一些新东西,可以继续改进你的代码。如果你发现任何错误,请告诉我!
感谢阅读。
如果您喜欢这篇文章,可以在此处关注更多内容
。Github。Medium。HackerRank。LinkedIn
。