1. Delete the trailing elements of an array
A simple way to clear or delete the trailing elements of an array is to change the value of the length property of the array.
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. Using object deconstruction to simulate named parameters
If you need to pass a series of options as arguments into a function, you might prefer to use an object (an objects) to define the configuration (config).
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 a stale, but effective, method that simulates named parameters in JavaScript. However, the way you handle config in dosomething is a little cumbersome. In ES2015, you can use object deconstruction directly.
function dosomething ({foo = ' Hi ', bar = ' yo! ', Baz = 13}) {
// ...
}
If you want this parameter to be optional, it is also very simple.
function dosomething ({foo = ' Hi ', bar = ' yo! ', Baz = 13} = {}) {
// ...
}
3. Using object deconstruction to manipulate arrays
You can use the syntax of an object's deconstruction to get the elements of an array:
Const Csvfileline = ' 1997,john doe,us,[email protected],new York ';
const {2:country, 4:state} = Csvfileline.split (', ');
4. Using range values in the switch statement
You can use the following technique to write a switch statement that satisfies a range value:
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
When using async/await, you can use Promise.all to await multiple async functions.
Await Promise.all ([Anasynccall (), Thisisalsoasync (), Onemore ()])
6. Create a plain (pure) object
You can create a 100% pure object that does not inherit any attributes from object or method (for example, constructor,tostring (), etc.).
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 not only character an object, but also format the output JSON object.
Const OBJ = {
Foo: {bar: [One, one, all,], 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 elements from an array
In ES2015, there is the syntax for the collection. By using the collection syntax and the spread operation, it is easy to remove duplicate elements:
Const REMOVEDUPLICATEITEMS = arr = [... new Set (arr)];
Removeduplicateitems ([$, ' foo ', ' A ', ' foo ', True, true]);
= [All, Foo, true]
9. Tiling multidimensional Arrays
With the spread operation, you can easily tile nested multidimensional arrays:
Const ARR = [11, [22, 33], [44, 55], 66];
Const FLATARR = [].concat (... arr.); = [11, 22, 33, 44, 55, 66]
Unfortunately, the above method only applies to two-dimensional arrays. However, with recursion, we can tile nested arrays of any dimension.
Unction 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]
That's all! I hope these tips can help you write more beautiful JS code! If not enough, then use Fundebug to do your aid!
Featured Reviews
· Ethan B Martin: This switch is very clever, but not recommended. Please do not encourage developers to write JS code in this way. We used to have an engineer write this, and later in the code review, caused a lot of reading misery. Fortunately, we can refactor it into more readable code in time. You might want to compare the difference between Swtich and if:
function GetWaterState1 (Tempincelsius) {
let state;
·
switch (TRUE) {
case (Tempincelsius = 0):
state = ' Solid ';
break;
case (Tempincelsius 100):
state = ' Liquid ';
break;
Default:
state = ' gas ';
·}
return state;
·}
function GetWaterState2 (Tempincelsius) {
if (Tempincelsius = 0) {
return ' Solid ';
·}
if (Tempincelsius 100) {
return ' Liquid ';
·}
return ' gas ';
}
The second formulation has several advantages:
A) Less code volume, more readable; B) You do not need to declare a local variable, the reader will not always have to track how you make changes to this variable; C) switch (true) can really make people baffled.
· Flo Sloot: Great article! However, the sixth trick is not recommended unless you must use it. Because it performs very slowly and takes up more space. Because V8 does not optimize for empty objects.
?
5 minutes to master JavaScript tips