In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you what are the logic judgment and optimization skills of JavaScript grammar and React JSX grammar. I hope you will gain something after reading this article. Let's discuss it together.
JavaScript grammar text nested hierarchical optimization function supply (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; / / condition 1: fruit exists if (fruit) {/ / condition 2: belongs to red fruit if (redFruits.includes (fruit)) {console.log ('red fruit') / / condition 3: the number of fruits is more than 10 if (quantity > 10) {console.log ('number more than 10');} else {throw new Error ('no fruit!');}}
According to the analysis of the above conditions, there are three layers of if condition nesting.
If the invalid condition is dropped in advance, the multiple nesting level of if else is reduced to one layer, which is easier to understand and maintain.
Function supply (fruit, quantity) {const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; if (! fruit) throw new Error ('no fruit'); / / condition 1: when fruit is invalid, deal with error if (! redFruits.includes (fruit)) return; / / condition 2: advance return console.log ('red fruit') when it is not red fruit / / condition 3: the number of fruits is more than 10 if (quantity > 10) {console.log ('number > 10');}} optimal treatment of multiple conditional branches
When you need enumerated values to handle different business branch logic, the first reaction is to write down the if else? Let's take a look:
Function pick (color) {/ / choose fruit if (color = 'red') {return [' apple', 'strawberry'];} else if (color =' yellow') {return ['banana',' pineapple'];} else if (color = 'purple') {return [' grape', 'plum'];} else {return [];}}
In the above implementation:
If else has too many branches
If else is more suitable for conditional interval judgment, while switch case is more suitable for branch judgment of specific enumerated values.
After optimizing the above code using switch case:
Function pick (color) {/ / choose fruit switch (color) {case 'red': return [' apple', 'strawberry']; case' yellow': return ['banana',' pineapple']; case 'purple': return [' grape', 'plum']; default: return [];}}
The optimized switch case code looks neatly formatted and clear, but it's still tedious. Continue to optimize:
With the {key: value} structure of Object, we can enumerate all cases in Object, and then use key as an index to get the content directly through Object.key or Object [key]
Const fruitColor = {red: ['apple',' strawberry'], yellow: ['banana',' pineapple'], purple: ['grape',' plum'],} function pick (color) {return fruitColor [color] | | [];}
Using Map data structures, real (key, value) key-value pair structures
Const fruitColor = new Map (). Set ('red', [' apple', 'strawberry']). Set (' yellow', ['banana',' pineapple']). Set ('purple', [' grape', 'plum']); function pick (color) {return fruitColor.get (color) | | [];}
After optimization, the code is simpler and easier to extend.
For better readability, you can also define objects in a more semantic way, and then use Array.filter to achieve the same effect.
Const fruits = [{name: 'apple', color:' red'}, {name: 'strawberry', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'pineapple', color:' yellow'}, {name: 'grape', color:' purple'}, {name: 'plum', color:' purple'}] Function pick (color) {return fruits.filter (f = > f.color = = color);} simplify logical judgment with new array features
Clever use of the new array features provided in ES6 also makes it easier for us to deal with logical judgments.
Multi-condition judgment
When you encounter multiple judgment conditions when coding, instinctively write down the following code (in fact, it is also the process-oriented code that best expresses business logic).
Function judge (fruit) {if (fruit = 'apple' | | fruit = =' strawberry' | | fruit = = 'cherry' | | fruit =' cranberries') {console.log ('red');}}
But when there are 10 or more type in the future, we can only continue to add | | to maintain the code?
Try Array.includes ~
/ / extract the judgment conditions into an array const redFruits = ['apple',' strawberry', 'cherry',' cranberries']; function judge (type) {if (redFruits.includes (fruit)) {console.log ('red') }} determine whether all items in the array satisfy certain conditions const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function match () {let isAllRed = true / / judgment condition: all fruits must be red for (let f of fruits) {if (! isAllRed) break; isAllRed = (f.color = 'red');} console.log (isAllRed); / / false}
In the above implementation, the main purpose is to deal with that all items in the array are qualified.
This logic can be easily implemented using Array.every:
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; function match () {/ / condition: all fruits must be red const isAllRed = fruits.every (f = > f.color = = 'red'); console.log (isAllRed) / / false} to determine whether an item in the array satisfies the condition
Array.some, which mainly deals with scenarios that determine whether an item in the array satisfies the condition.
If you want to know if there is any red fruit, you can use the Array.some method directly:
Const fruits = [{name: 'apple', color:' red'}, {name: 'banana', color:' yellow'}, {name: 'grape', color:' purple'}]; / / condition: whether there is a red fruit const isAnyRed = fruits.some (f = > f.color = = 'red')
There are many other new array features, such as Array.find, Array.slice, Array.findIndex, Array.reduce, Array.splice, and so on, which you can choose to use in real-world scenarios.
Function defaults use the default parameter const buyFruit = (fruit,amount) = > {if (! fruit) {return} amount = amount | | 1; console.log (amount)}
We often need to deal with the default values of some parameters within the function, the above code is not unfamiliar to everyone, using the default parameters of the function can help to deal with this scenario.
Const buyFruit = (fruit,amount = 1) = > {if (! fruit) {return} console.log (amount,'amount')}
We can see how the default parameters are implemented through the translation of Babel.
As you can see from the above translation, the default parameter is used only if the parameter is undefined.
The execution results of the test are as follows:
BuyFruit ('apple',''); / / amountbuyFruit (' apple',null); / / null amountbuyFruit ('apple'); / / 1 amount
So when using the default parameter, we need to note that the default parameter amount=1 is not equal to amount | | 1.
Use deconstruction and default parameters
When the function argument is an object, we can use deconstruction combined with default parameters to simplify the logic.
Before:
Const buyFruit = (fruit,amount) = > {fruit = fruit | | {}; if (! fruit.name | |! fruit.price) {return;}. Amount = amount | | 1; console.log (amount)}
After:
Const buyFruit = ({name,price} = {}, amount) = > {if (! name | |! prices) {return;} console.log (amount)} complex data deconstruction
When dealing with simpler objects, the deconstruction works very well with the default parameters, but in some complex scenarios, we may be faced with more complex structures.
Const oneComplexObj = {firstLevel: {secondLevel: [{name: ", price:"}]}}
At this time, if you deconstruct to get the value in the object.
Const {firstLevel: {secondLevel: [{name,price] = []} = {}} = oneComplexObj
Readability is poor, and defaults for multi-layer deconstruction and data exceptions need to be taken into account.
In this case, if the lodash library is used in the project, you can use the lodash/get method in it.
Import lodashGet from 'lodash/get';const {name,price} = lodashGet (oneComplexObj,'firstLevel.secondLevel [0]', {}); policy mode optimizes branch logic processing
Policy pattern: define a series of algorithms, encapsulate them one by one, and make them interchangeable.
Usage scenario: the policy pattern belongs to the object behavior pattern. When you encounter instance objects with the same behavior interface and different logic implementations within the behavior, you can use the policy pattern; or when a group of objects can dynamically select one of several behaviors as needed, you can also use the policy pattern. Here we take the second case as an example:
Before:
Const TYPE = {JUICE:'juice', SALAD:'salad', JAM:'jam'} function enjoy ({type = TYPE.JUICE,fruits}) {if (! fruits | |! fruits.length) {console.log ('Please buy fruit first!') ; return;} if (type = TYPE.JUICE) {console.log ('squeezed juice'); return 'juice';} if (type = TYPE.SALAD) {console.log ('making salad...'); return 'Lassa';} if (type = TYPE.JAM) {console.log ('making jam'); return 'jam';} return } enjoy ({type:'juice',fruits})
Use idea: define policy objects to encapsulate different behaviors, provide policy selection interfaces, and invoke corresponding behaviors when different rules are used.
After:
Const TYPE = {JUICE:'juice', SALAD:'salad', JAM:'jam'} const strategies = {[TYPE.JUICE]: function (fruits) {console.log ('squeezed juice'); return 'juice';}, [TYPE.SALAD]: function (fruits) {console.log ('making salad...'); return 'salad' }, [TYPE.JAM]: function (fruits) {console.log ('making jam...'); return 'jam';} function enjoy ({type = TYPE.JUICE,fruits}) {if (! type) {console.log ('Please enjoy it!') ; return;} if (! fruits | |! fruits.length) {console.log ('Please buy fruit first') ; return;} return strategies [type] (fruits);} enjoy ({type:'juice',fruits}); React JSX logic judgment optimization of the framework
JSX is a JavaScript syntax extension that looks a lot like XML. Generally, JSX is used to describe the interface information in React, and ReactDOM.render () renders the JSX interface information to the page.
JavaScript expressions are supported in JSX, daily common loop output subcomponents, ternary expression judgment, and more complex direct abstraction of a function.
Writing so many JavaScript expressions in JSX makes the overall code look a little messy. Try to optimize it!
JSX-Control-Statements
JSX-Control-Statements is a Babel plug-in that extends the ability of JSX to handle conditional judgment and loops in the form of tags.
If tag
The tag content is rendered only when condition is true, which is equivalent to the simplest ternary expression.
Before:
{condition ()? 'Hello Worldwide': null}
After:
Hello World!
Note: it has been abandoned and tags can be used for complex condition judgments.
Choose tag
At least one tag and an optional tag are included under the tag.
The tag content is rendered only when condition is true, which is equivalent to a branch of if conditional judgment.
The tag is equivalent to the last else branch.
Before:
{test1? IfBlock1: test2? IfBlock2: ElseBlock}
After:
IfBlock1 IfBlock2 ElseBlock For tag
Tags need to declare of and each attributes.
Of receives objects that can be accessed using iterators.
Each represents the element currently pointing to when the iterator accesses.
Before:
{(this.props.items | | []) .map (item = > {return {item.title}})}
After:
{item.title}
Note: tags cannot be used as root elements.
With tag
The tag provides the function of passing parameters in variables.
Before:
RenderFoo = (foo) = > {return {foo};} / / expression call {this.renderFoo (47)} in JSX
After:
{foo}
Using these tags to optimize code can reduce the explicit JavaScript expressions that exist in JSX and make our code look more concise, but the ability of these tags to encapsulate needs to be converted to equivalent JavaScript expressions at compile time.
After reading this article, I believe you have a certain understanding of "what are the logic judgment and optimization skills of JavaScript grammar and React JSX grammar". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.