原文 - Learn these neat JavaScript tricks in less than 5 minutesjavascript
一些平常开发技巧,意译了。java
最简单的清空和截短数组的方法就是改变 length
属性:数组
const arr = [11, 22, 33, 44, 55, 66];
// 截取
arr.length = 3;
console.log(arr); //=> [11, 22, 33];
// 清空
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined
复制代码
之前,当咱们但愿向一个函数传递多个参数时,可能会采用配置对象
的模式:less
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;
// ...
}
复制代码
这是一个古老可是有效的模式,有了 ES2015
的对象结构,你能够这样使用:async
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
// ...
}
复制代码
若是你须要这个配置对象
参数变成可选的,也很简单:函数
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
// ...
}
复制代码
使用对象解构将数组项赋值给变量:ui
const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');
复制代码
注:本例中,
2
为split
以后的数组下标,country
为指定的变量,值为US
this
switch
语句中使用范围这是一个在 switch
语句中使用范围的例子:spa
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;
}
复制代码
await
多个 async
函数await
多个 async
函数并等待他们执行完成,咱们能够使用 Promise.all
:code
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
复制代码
你能够建立一个 100% 的纯对象,这个对象不会继承 Object
的任何属性和方法(好比 constructor
,toString()
等):
const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
复制代码
JSON
代码JSON.stringify
不只能够字符串
化对象,它也能够格式化你的 JSON
输出:
const obj = {
foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }
};
// 第三个参数为格式化须要的空格数目
JSON.stringify(obj, null, 4);
// =>"{
// => "foo": {
// => "bar": [
// => 11,
// => 22,
// => 33,
// => 44
// => ],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
// => }
// => }
// =>}"
复制代码
使用 ES2015
和扩展运算符,你能够轻松移除数组中的重复项:
const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
复制代码
注:只适用于数组内容为
基本数据类型
使用扩展运算符能够快速扁平化数组:
const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
复制代码
不幸的是,上面的技巧只能适用二维数组
,可是使用递归,咱们能够扁平化任意纬度数组:
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]
复制代码
就这些,但愿上面这些优雅的技巧可能帮助你编写更漂亮的JavaScript
。