1.清除或截断数组
清除或截断数组而不重新分配数组的简单方法是更改其长度属性值:
const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined
2.用对象解构来模拟命名参数
当您需要将一组变量的选项传递给某个函数时,您已经在使用配置对象的可能性很高,如下所示:
doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
function doSomething(config) {
const foo = config.foo !== undefined ? config.foo : 'Hi';
const bar = config.bar !== undefined ? config.bar : 'Yo!';
const baz = config.baz !== undefined ? config.baz : 13;
// ...
}
这是一种古老而有效的模式,它试图模拟JavaScript中的命名参数。 函数调用看起来很好。 另一方面,配置对象处理逻辑不必要的冗长。 借助ES2015对象解构,您可以避开这种不利情况:
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {// ...}
如果你需要使配置对象成为可选的,那也很简单:
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {// ...}
3.数组项的对象解构
使用对象解构将数组项赋给单个变量:
const csvFileLine = '1997,John Doe,US,[email protected],New York';
const { 2: country, 4: state } = csvFileLine.split(',');
4.用范围切换
以下是在switch语句中使用范围的简单技巧:
function getWaterState(tempInCelsius) {
let state;
switch (true) {
case (tempInCelsius <= 0):
state = 'Solid';
break;
case (tempInCelsius > 0 && tempInCelsius < 100):
state = 'Liquid';
break;
default:
state = 'Gas';
}
return state;
}
5.等待异步/等待多个异步函数
可以通过使用Promise.all来等待多个异步函数完成:
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6.创建纯粹的对象
您可以创建一个100%纯的对象,它不会从Object继承任何属性或方法(例如,构造函数,toString()等)。
const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
7. Formatting JSON code
JSON.stringify可以做的不仅仅是将对象串化。 你也可以用它美化你的JSON输出:
const obj = {
foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }
};
// The third parameter is the number of spaces used to
// beautify the JSON output.
JSON.stringify(obj, null, 4);
// =>"{
// => "foo": {
// => "bar": [
// => 11,
// => 22,
// => 33,
// => 44
// => ],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
// => }
// => }
// =>}"
8.从阵列中删除重复的项目
通过使用ES2015集合以及Spread运算符,您可以轻松地从数组中删除重复的项目:
const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
9.展平多维数组
使用Spread运算符展平数组:
const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
上述技巧只适用于二维数组。 但是对于递归调用,我们可以使它适用于2维以上的数组:
function flattenArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ?
flattenArray(flattened) : flattened;
}
const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenArray(arr);
//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
译文:https://medium.freecodecamp.org/9-neat-javascript-tricks-e2742f2735c3
閱讀更多 全棧取經之路 的文章
關鍵字: Bing JSON JavaScript