科技和互联网

5分钟内学会这些超实用的Javascript窍门

从一开始只是为网页增加一些实时的动态效果,到现在的web前后端通吃,Javascript成了各机构统计的年度最流行语言。随着系统的复杂度增加,真的学会它,也绝非是一件容易的事。记得几年前,有人在Youtube上说,他花了整整2年的时间,终于可以认为自己学会了Javascript,但按照ES2015以后的Javascript标准来看,想从零开始成为Javascript专家,两年是远远不够的。
这些专业程序员的Javascript窍门都是既实用又节省时间,如果能在实际工作中随心所欲地写出这样的语句段落,是一件多么赏心悦目的事。
如何最简单地清空和截断一个数组?对象结构数组?如何按范围构造switch语句?等待多个异步函数?创建一个不继承任何方法属性的100%的纯对象?….. 其中,功能最强大的是用ES2015的展开运算符,如果结合集合,可以一步清除数组中的重复项。还有很多诀窍,请自己参考原文挖掘。

原文链接:https://medium.freecodecamp.org/9-neat-javascript-tricks-e2742f2735c3
原文抄录:

Learn these neat JavaScript tricks in less than 5 minutes

Alcides Queiroz
Time-saving techniques used by pros

  1. Clearing or truncating an array
    An easy way of clearing or truncating an array without reassigning it is by changing its length property value:

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. Simulating named parameters with object destructuring
Chances are high that you’re already using configuration objects when you need to pass a variable set of options to some function, like this:

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;
// …
}
This is an old but effective pattern, which tries to simulate named parameters in JavaScript. The function calling looks fine. On the other hand, the config object handling logic is unnecessarily verbose. With ES2015 object destructuring, you can circumvent this downside:

function doSomething({ foo = ‘Hi’, bar = ‘Yo!’, baz = 13 }) {
// …
}
And if you need to make the config object optional, it’s very simple, too:

function doSomething({ foo = ‘Hi’, bar = ‘Yo!’, baz = 13 } = {}) {
// …
}
3. Object destructuring for array items
Assign array items to individual variables with object destructuring:

const csvFileLine = ‘1997,John Doe,US,john@doe.com,New York’;
const { 2: country, 4: state } = csvFileLine.split(‘,’);
4. Switch with ranges
Here’s a simple trick to use ranges in switch statements:

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. Await multiple async functions with async/await
It’s possible to await multiple async functions to finish by using Promise.all:

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6. Creating pure objects
You can create a 100% pure object, which won’t inherit any property or method from Object (for example, constructor, toString() and so on).

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 can do more than simply stringify an object. You can also beautify your JSON output with it:

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. Removing duplicate items from an array
By using ES2015 Sets along with the Spread operator, you can easily remove duplicate items from an array:

const removeDuplicateItems = arr => […new Set(arr)];
removeDuplicateItems([42, ‘foo’, 42, ‘foo’, true, true]);
//=> [42, “foo”, true]
9. Flattening multidimensional arrays
Flattening arrays is trivial with Spread operator:

const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(…arr); //=> [11, 22, 33, 44, 55, 66]
Unfortunately, the above trick will only work with bidimensional arrays. But with recursive calls, we can make it suitable for arrays with more than 2 dimensions:

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]
And there you have it! I hope these neat little tricks help you write better and more beautiful JavaScript.

Tagged

我忍不住要留言