In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what JavaScript tips are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Array
Let's first take a look at some of the tips commonly used in arrays.
Array deduplication
ES6 provides several concise methods for array deduplication, but this method is not suitable for dealing with non-basic types of arrays. For basic types of array deduplication, you can use. New Set () to filter out duplicate values in the array and create a new array with only unique values.
Const array = [1, 1, 2, 3, 5, 5, 1] const uniqueArray = [... new Set (array)]; console.log (uniqueArray); > Result: (4) [1,2,3,5]
This is a new feature in ES6, and before ES6, we need to use more code to achieve the same effect. This technique applies to arrays that contain basic types: undefined, null, boolean, string, and number. If the array contains an object,function or other array, you need to use another method.
In addition to the above method, you can also use Array.from (new Set ()) to implement:
Const array = [1,1,2,3,5,5,1] Array.from (new Set (array)) > Result: (4) [1,2,3,5]
In addition, you can also use Array's .filter and indexOf () to implement:
Const array = [1,1,2,3,5,5,1] array.filter ((arr, index) = > array.indexOf (arr) = index) > Result: (4) [1,2,3,5]
Note that the indexOf () method returns the first array item that appears in the array. This is why we can compare the index returned by the indexOf () method with the current index in each iteration to determine whether the current item is duplicated.
Ensure the length of the array
When working with the grid structure, if the length of each row of the original data is not equal, you need to recreate the data. To ensure that each row of data is equal in length, you can use Array.fill to process:
Let array = Array (5). Fill (''); console.log (array); > Result: (5) [","]
Array mapping
Method that does not use Array.map to map array values.
Const array = [{name: 'desert', email: 'w3C pluse hotmail.com'}, {name:' Airen', email: 'airen@gmail.com'}] const name = Array.from (array, ({name}) = > name) > Result: (2) ["desert", "Airen"]
Array truncation
If you want to delete the value from the end of the array (delete the last item in the array), there is a faster alternative than using splice ().
For example, if you know the size of the original array, you can redefine the value of the array's length property to delete the value from the end of the array:
Let array = [0,1,2,3,4,5,6,7,8,9] console.log (array.length) > Result: 10array.length = 4console.log (array) > Result: (4) [0,1,2,3]
This is a very simple solution. However, the slice () method runs faster and performs better:
Let array = [0,1,2,3,4,5,6,7,8,9]; array = array.slice (0,4); console.log (array); > Result: [0,1,2,3]
Filter out the false value in the array
If you want to filter the false values in the array, such as 0, undefined, null, false, you can do so through the map and filter methods:
Const array = [0,1, '0mm,' 1century, 'desert', 'w3cplus.com, undefined, true, false, null,' undefined', 'null', NaN,' NaN','1' + 0] array.map (item = > {return item}) .filter (Boolean) > Result: (10) [1, "0", "1", "desert", "w3cplus.com", true, "undefined", "null", "NaN" "10"]
Get the last item of the array
When the slice () of the array is positive, the items of the array are truncated from the beginning of the array, and if the value is a negative integer, the items of the array can be obtained from the end of the array.
Let array = [1,2,3,4,5,6,7] const firstArrayVal = array.slice (0,1) > Result: [1] const lastArrayVal = array.slice (- 1) > Result: [7] console.log (array.slice (1)) > Result: (6) [2,3,4,5,6,7] console.log (array.slice (array.length)) > Result: []
As shown in the above example, use array.slice (- 1) to get the last item of the array, and you can also get the last item of the array in the following way:
Console.log (array.slice (array.length-1)) > Result: [7]
Filter and sort the list of strings
You may have a list of many names and you need to filter out duplicate names and sort them alphabetically.
In our example, we are going to keep a list of words in different versions of JavaScript, but you can find that there are many duplicate keywords and they are not in alphabetical order. So this is a perfect list of strings (arrays) to test our JavaScript trivia.
Var keywords = ['do',' if', 'in',' for', 'new',' try', 'var',' case', 'else',' enum', 'null',' this', 'true',' void', 'with',' break', 'catch',' class', 'const',' false', 'super',' throw', 'while',' delete', 'export' 'import', 'return',' switch', 'typeof',' default', 'extends',' finally', 'continue',' debugger', 'function',' do', 'if',' in', 'for',' int', 'new',' try', 'var',' byte', 'case',' char', 'else',' enum', 'goto',' long', 'null' 'this', 'true',' void', 'with',' break', 'catch',' class', 'const',' false', 'final',' float', 'short',' super', 'throw',' while', 'delete',' double', 'export',' import', 'native',' public', 'return',' static', 'switch',' throws', 'typeof' 'boolean', 'default',' extends', 'finally',' package', 'private',' abstract', 'continue',' debugger', 'function',' volatile', 'interface',' protected', 'transient',' implements', 'instanceof',' synchronized', 'do',' if', 'in',' for', 'let',' new', 'try',' var', 'case' 'else', 'enum',' eval', 'null',' this', 'true',' void', 'with',' break', 'catch',' class', 'const',' false', 'super',' throw', 'while',' yield', 'delete',' export', 'import',' public', 'return',' static', 'switch',' typeof', 'default' 'extends', 'finally',' package', 'private',' continue', 'debugger',' function', 'arguments',' interface', 'protected',' implements', 'instanceof',' do', 'if',' in', 'for',' let', 'new',' try', 'var',' case', 'else',' enum', 'eval',' null', 'this' 'true', 'void',' with', 'await',' break', 'catch',' class', 'const',' false', 'super',' throw', 'while',' yield', 'delete',' export', 'import',' public', 'return',' static', 'switch',' typeof', 'default',' extends', 'finally',' package', 'private' 'continue', 'debugger',' function', 'arguments',' interface', 'protected',' implements', 'instanceof']
Because we don't want to change our original list, we're going to use a higher-order function called filter, which will return a new filtered array based on the callback method we passed. The callback method compares the index of the current keyword in the original list with the index in the new list, and push the current keyword to the new array only if the index matches.
Finally, we are going to sort the filtered list using the sort method, where sort accepts only one comparison method as a parameter and returns the alphabetical list.
Using the arrow function under ES6 looks easier:
Const filteredAndSortedKeywords = keywords .filter ((keyword, index) = > keywords.lastIndexOf (keyword) = index) .sort ((a, b) = > a
< b ? -1 : 1); 这是最后过滤和排序后的JavaScript保留字列表: console.log(filteredAndSortedKeywords);>Result: ['abstract',' arguments', 'await',' boolean', 'break',' byte', 'case',' catch', 'char',' class', 'const',' continue', 'debugger',' default', 'delete',' do', 'double',' else', 'enum',' eval', 'export',' extends', 'false',' final', 'finally' 'float', 'for',' function', 'goto',' if', 'implements',' import', 'in',' instanceof', 'int',' interface', 'let',' long', 'native',' new', 'null',' package', 'private',' protected', 'public',' return', 'short',' static', 'super',' switch', 'synchronized' 'this', 'throw',' throws', 'transient',' true', 'try',' typeof', 'var',' void', 'volatile',' while', 'with',' yield']
Empty the array
If you define an array, then you want to clear it. Usually, you would do this:
Let array = [1,2,3,4]; function emptyArray () {array = [];} emptyArray ()
However, there is a more efficient way to empty the array. You can write like this:
Let array = [1,2,3,4]; function emptyArray () {array.length = 0;} emptyArray ()
Flatten multidimensional array
Use. Operator to flatten the multidimensional array:
Const arr = [1, [2, 'desert'], 3, ['blog',' 1 desert, 2, 3]] const flatArray = [] .concat (... arr) console.log (flatArray) > Result: (8) [1, 2, "desert", 3, "blog", "1", 2, 3]
However, the above method only applies to two-dimensional arrays. However, through recursive calls, you can use it to apply to arrays below two dimensions:
Function flattenArray (arr) {const flattened = [] .concat (.. arr); return flattened.some (item = > Array.isArray (item))? FlattenArray (flattened): flattened;} const array = [1, [2, 'desert'], 3, [['blog',' 1'], 2, 3]] const flatArr = flattenArray (array) console.log (flatArr) > Result: (8) [1, 2, "Desert", 3, "blog", "1", 2, 3]
Get the maximum and minimum values from the array
You can use Math.max and Math.min to fetch the maximum and minimum values in an array:
Const numbers = [15, 80,-9, 90,-99] const maxInNumbers = Math.max.apply (Math, numbers) const minInNumbers = Math.min.apply (Math, numbers) console.log (maxInNumbers) > Result: 90console.log (minInNumbers) > Result:-99
You can also use ES6's. Operator to complete:
Const numbers = [1,2,3,4]; Math.max (... numbers) > Result: 4Math.min (... numbers) > > Result: 1
Object
There are also some tricks when manipulating objects.
Use. An operation conforms to an object in a union object or array.
It also uses ES's. Operators can replace human operations, merge objects, or merge objects in an array.
/ / merge objects const obj1 = {name: 'desert', url: 'w3cplus.com'} const obj2 = {name: 'airen', age: 30} const mergingObj = {... obj1,... obj2} > Result: {name: "airen", url: "w3cplus.com", age: 30} / / merge objects in the array const array = [{name:' desert' Email: 'w3cplusaccoungmail.com'}, {name:' Airen', email: 'airen@gmail.com'}] const result = array.reduce ((accumulator, item) = > {return {... accumulator, [item.name]: item.email}}, {}) > Result: {Desert: "w3cplus@gmail.com", Airen: "airen@gmail.com"}
Conditionally add object properties
It is no longer necessary to create two different objects based on a condition to make it have specific properties. To do this, use. Operators are the simplest.
Const getUser = (emailIncluded) = > {return {name: 'desert', blog: 'w3cplusdesert,. EmailIncluded & & {email:' w3cplusdesert hotmail.com'} const user = getUser (true) console.log (user) > Result: {name: "desert", blog: "w3cplus", email: "w3cplus@hotmail.com"} const userWithoutEmail = getUser (false) console.log (userWithoutEmail) > Result: {name: "desert" Blog: "w3cplus"}
Deconstruct the original data
When you use the data, you can put all the data in one object. At the same time, I want to get the data I want in this data object. This can be done here using the Destructuring feature of ES6. For example, you want to divide the data in the following obj into two parts:
Const obj = {name: 'desert', blog: 'w3cplusdesert, email:' w3cplusthermal hotmail.compose, joined: '2019-06-19, followers: 45} let user = {}, userDetails = {} ({name: user.name, email: user.email,... userDetails} = obj) > {name: "desert", blog: "w3cplus", email: "w3cplus@hotmail.com", joined: "2019-06-19" Followers: 45} console.log (user) > Result: {name: "Desert", email: "w3cplus@hotmail.com"} console.log (userDetails) > Result: {blog: "w3cplus", joined: "2019-06-19", followers: 45}
Dynamically change the key of an object
In the past, we had to first declare an object and then assign a property if a dynamic property name was needed. In the past, this could not have been achieved declaratively. However, in ES6, we can achieve:
Const dynamicKey = 'email'let obj = {name:' desert', blog: 'w3cplusdesert, [dynamicKey]:' w3cplusthermal hotmail.com'} console.log (obj) > Result: {name: "desert", blog: "w3cplus", email: "w3cplus@hotmail.com"}
Determine the data type of the object
Use Object.prototype.toString with closures to determine the object data type:
Const isType = type = > target = > `[object ${type}]` = Object.prototype.toString.call (target) const isArray = isType ('Array') ([1,2,3]) console.log (isArray) > Result: true
The above code is equivalent to:
Function isType (type) {return function (target) {return `[object ${type}]` = Object.prototype.toString.call (target)}} isType ('Array') > Result: true
Or:
Const isType = type = > target = > `[object ${type}]` = Object.prototype.toString.call (target) const isString = isType ('String') const res = isString ((' 1')) console.log (res) > Result: true
Check whether an object has an attribute
When you need to check whether a property exists in an object, you might do this:
Var obj = {name: 'desert'}; if (obj.name) {console.log (true) / / > Result: true}
This is OK, but you need to know that there are two native ways to solve such problems. The in operator and Object.hasOwnProperty, which can be used by any object that inherits from Object.
Var obj = {name: 'desert'}; obj.hasOwnProperty ('name'); / / > true'name' in obj; / / > trueobj.hasOwnProperty (' valueOf'); / / > false, valueOf inherits from the prototype chain 'valueOf' in obj; / / > true
The depth of the check property is different, in other words, hasOwnProperty only returns true when it has this property itself, while the in operator does not distinguish between attributes that come from itself or inherit from the prototype chain.
This is another example:
Var myFunc = function () {this.name = 'desert';}; myFunc.prototype.age ='10 days';var user = new myFunc (); user.hasOwnProperty ('name'); > Result: trueuser.hasOwnProperty (' age'); > Result: false, / / because age comes from the prototype chain
Create a pure object
Using Object.create (null), you can create a pure object that does not inherit any methods from the Object class (for example, constructor, toString (), and so on):
Const pureObject = Object.create (null); console.log (pureObject); / / = > {} console.log (pureObject.constructor); / / = > undefinedconsole.log (pureObject.toString); / / = > undefinedconsole.log (pureObject.hasOwnProperty); / / = > undefined
Data type conversion
The data types in JavaScript include Number, String, Boolean, Object, Array and Function, etc., and the conversion of data types will be encountered in practical use. There are also some tricks when converting data types.
Convert to Boolean
Boolean values in addition to true and false, JavaScript can treat all other values as "real" or "false." Unless otherwise defined, the values in JavaScript are real except for 0,'', null, undefined, NaN, and false.
We can easily use it between true and false! Operator, which also converts the type to Boolean. For example:
Const isTrue =! 0 Result Const isFasle =! 1 Result Const isFasle =! 0 /! 0 = > true,true is falseconsole.log (isTrue) > Result: trueconsole.log (typeof isTrue) > Result: 'boolean'
This type of conversion is very convenient in conditional statements, such as treating! 1 as false.
Convert to string
We can use the operator + followed by an empty set of quotes''to quickly convert a number or Boolean value to a string:
Const val = 1 + 'const val2 = false +' console.log (val) > Result: "1" console.log (typeof val) > Result: "string" console.log (val2) > Result: "false" console.log (typeof val2) > Result: "string"
Convert to numeric value
As we saw above, you can convert a numeric value to a string by using + followed by an empty string''. On the contrary, you can quickly achieve the opposite effect by using the addition operator +.
Let int = '12'int = + intconsole.log (int) > Result: 12console.log (typeof int) > Result:' number'
Boolean values can be converted to numeric values in the same way:
Console.log (+ true) > Return: 1console.log (+ false) > Return: 0
In some contexts, + is interpreted as a join operator, not an addition operator. When this happens and you want to return an integer instead of a floating-point number, you can use two tilde ~ ~. The double tilde ~ ~ is called the bitwise unoperator, which is equivalent to-n-1. For example, ~ 15 =-16. This is because-(- n-1)-1 = n + 1-1 = n. In other words, ~-16 = 15.
We can also use ~ ~ to convert a numeric string to an integer:
Const int = ~ '15'console.log (int) > Result: 15console.log (typeof int) > Result:' number'
Similarly, the NOT operator can also be used for Boolean values: ~ true =-2 received false =-1.
Convert floating point numbers to integers
You usually use Math.floor (), Math.ceil (), or Math.round () to convert floating-point numbers to integers. There is also a faster way in JavaScript to truncate floating-point numbers to integers using | (bits or operators).
Console.log; > Result: 23console.log (- 23.9 | 0); > Result:-23
| the behavior depends on whether you are dealing with positive or negative numbers, so it is best to use this shortcut only when you are sure.
If n is a positive number, then n | 0 effectively rounds down. If n is negative, it is effectively rounded. More precisely, this operation deletes the contents after the decimal point and truncates the floating point to an integer. You can also use ~ ~ to get the same rounding effect, and as mentioned above, virtually any bit operator forces a floating-point number to be an integer. These special operations are effective because once forced to an integer, the value remains the same.
| it can also be used to delete any number of numbers from the end of an integer. This means that we do not need to convert types like this:
Let str = "1553"; Number (str.substring (0, str.length-1)); > Result:
We can use the | operator instead as follows:
Console.log (1553 / 10 | 0) > Result: 155console.log (1553 / 1000 | 0) > Result: 15console.log (1553 / 1000 | 0) > Result: 1
Use! Operator to convert Boolean values
Sometimes we need to check for the existence of a variable or check whether the value has a valid value, and return the true value if it exists. In order to do such a verification, we can use! Operator to implement is very convenient and simple.
For variables, you can use! variable to detect, as long as the value of the variable is: 0, null, "", undefined, or NaN will return false, and vice versa. For example, the following example:
Function Account (cash) {this.cash = cash; this.hasMoney =!! cash;} var account = new Account (100.50); console.log (account.cash); > Result: 100.50console.log (account.hasMoney); > Result: truevar emptyAccount = new Account (0); console.log (emptyAccount.cash); > Result: 0console.log (emptyAccount.hasMoney); > Result: false
In this example, as long as the value of account.cash is greater than 0, the value returned by account.hasMoney is true.
It can also be used! Operator converts a truthy or false value to a Boolean value:
! "/ / > falsehoods are undefined / / > falsehoods are undefined / / > falsehoods are undefined!" hello "/ > trueworthy secrets 1 / > trueworthy! {} / / > trueworthy! [] / > true is all the contents of this article entitled" what are the tips for using JavaScript? "Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.