[This is the 18th day of my participation in the Gengwen Challenge. For details, see “Gengwen Challenge”]
JavaScript is a flexible language with many features that are different from other languages. This article shares 7 JavaScript coding tips that you can use in everyday development to enjoy the elegance of programming. For more coding tips, see 18 Tips for JavaScript Code and 24 Tips for JavaScript Code Optimization.
1. Conditionally extend object properties
Extended operators… Is now the project’s favorite operator to use, array, object operations become concise and elegant. Here’s another way to use it, using its conditional extension object properties.
We can use the extension operator… To conditionally quickly add properties to JavaScript objects.
For example, if you have a match between England at home and Scotland at home, you can add homeVictory: true.
const conditionAddField = (scoreHome, scoreVisiting) => { return { home: "England", visiting: "Scottish", ... (scoreHome > scoreVisiting && { homeVictory: true }), }; }; console.log(conditionAddField(2, 1)); // { home: 'England', visiting: 'Scottish', homeVictory: true } console.log(conditionAddField(1, 1)); // { home: 'England', visiting: 'Scottish' }Copy the code
The above code implements conditional extended object properties, and the same applies to arrays.
2. Check whether the object attribute exists
The in operator, which most people probably don’t use in projects, can actually be used to check whether an object has attributes, as follows:
const result = {
home: "England",
visiting: "Scottish",
scoreResult: "2:1",
};
console.log("scoreResult" in result); // true
console.log("isFinish" in result); // false
Copy the code
3. Use variables to deconstruct attributes
As most of you know, when you want to assign a property value to a variable, you can use the following method:
const result = {
home: "England",
visiting: "Scottish",
};
const { home: homeTeam } = result;
console.log(homeTeam); // England
Copy the code
Now let’s look at another way to deconstruct, as follows:
const result = {
home: "England",
visiting: "Scottish",
};
const keyName = "visiting";
const { [keyName]: homeTeam } = result;
console.log(homeTeam); // Scottish
Copy the code
4. Check the array for false values
For array operations, it’s important to be familiar with the three methods: filter, some, and every. Boolean uses Boolean as follows:
const arrayTest = [ null, false, "UEFA European Football Championship", undefined, 0, ]; Const arrayFiltered = ArrayTest.filter (Boolean); console.log(arrayFiltered); // ['UEFA European Football Championship'] // Check whether at least one value is true const orResult = arraytest. some(Boolean); console.log(orResult); Const andResult = arrayTest.every(Boolean); console.log(andResult); // falseCopy the code
In dynamic validation or form configuration scenarios to verify the correctness of input items, use some to implement the condition of or and every to implement the condition of and, such as the following code:
Implementation may not be optimal, just for illustrative purposes
Const ageValidationOptions = {title: "age ", condition: "and", validations: [{description:" must be number ", fn: (val) = >! IsNaN (val),}, {the description: "must be a scale of 0-120", fn: (val) = > val < 120 && val > 0,},]}; Const orValidationOptions = {title: "test ", condition: "or", validations: [{description:" number ", fn: (val) = >! IsNaN (val),}, {the description: "greater than zero, fn: (val) = > parseInt (val, 10) > 0,},]}; const validationCondition = { and: (validations, inputVal) => validations.every((item) => item.fn(inputVal)), or: (validations, inputVal) => validations.some((item) => item.fn(inputVal)), }; const validationHelper = ({ condition, validations }, inputVal) => { return validationCondition[condition](validations, inputVal); }; console.log(validationHelper(ageValidationOptions, "140")); // false console.log(validationHelper(ageValidationOptions, 20)); // true console.log(validationHelper(orValidationOptions, 20)); // true console.log(validationHelper(orValidationOptions, "a")); // falseCopy the code
5. Use variables to add or obtain object properties
Usually you need to get the attribute name of an object dynamically through a variable or add a new attribute by using [attrName], such as:
const result = { home: "England", visiting: "Scottish", }; const addField = (key, value, object) => { object[key] = value; return object; }; console.log(addField("isFinish", true, result)); // {home: 'England', visiting: 'Scottish', isFinish: true} // console.log(result[fieldName]); // EnglandCopy the code
The above code is just to show you how to dynamically add object properties. Using this in a real project would involve copying objects.
6. Flatten arrays
The prototype Array has a method flat that creates an Array from an Array of arrays:
The flat() method recurses through the array at a specified depth and returns a new array combining all the elements with the elements in the subarray it traverses.
grammar
var newArray = arr.flat([depth])
parameter
Depth optional. Specifies the structure depth to extract the nested array. The default value is 1.
The return value
A new array containing all the elements of the subarray and the array.
const arrayTest = [{ id: 101 }, [{ id: 102 }], [{ id: 103 }]];
const arrayFlatted = arrayTest.flat();
console.log(arrayFlatted); // [ { id: 101 }, { id: 102 }, { id: 103 } ]
Copy the code
You can also define a depth level that specifies the depth at which the nested array structure should be flattened. Such as:
const arrayTest = [0, 1, 2, [[[3, 4, [5]]]]]; console.log(arrayTest.flat(2)); // [ 0, 1, 2, [ 3, 4, [ 5 ] ] ] console.log(arrayTest.flat(3)); // [0, 1, 2, 3, 4, [5]]Copy the code
7.console.log
The use of
Use console logging to output information, especially to track variable values during debugging. Share a trick with console.log(). For example, to print a set of data, like this:
const person = (name, color, countries) => { return { name, color, countries, }; }; Const person1 = person(" cristiano Ronaldo ", "black", "Portugal "); Const person2 = person(" romelu Lukaku ", "white", "Belgium "); Const person3 = person(" Patrick Schick ", "blue", "Czechs "); console.log({ person1, person2, person3 });Copy the code
The output is as follows:
{person1: {name: 'Cristiano Ronaldo ', color: 'black', countries:' Portugal '}, person2: {name: 'Romelu Lukaku ', color: 'white', countries: 'Belgium'}, person3: {name: 'Patrick Schick ', color: 'blue', countries:' Czech '}}Copy the code
The log output function console.table() is passed an array. It prints the array as a table for comparison, as follows:
const person = (name, color, countries) => { return { name, color, countries, }; }; Const person1 = person(" cristiano Ronaldo ", "black", "Portugal "); Const person2 = person(" romelu Lukaku ", "white", "Belgium "); Const person3 = person(" Patrick Schick ", "blue", "Czechs "); console.table([person1, person2, person3]);Copy the code
The input results are as follows (the first is the terminal print effect, the second is the browser print effect) :
conclusion
Hopefully, these tips will improve your coding skills, and feel free to share more JavaScript tips in the comments!