1. Global replacement
We know that the string function replace () only replaces the first occurrence Condition.
You can replace all occurrences by adding /g at the end of the regular expression.
var example = "potato potato"; console.log(example.replace(/pot/, "tom")); // "tomato potato" console.log(example.replace(/pot/g, "tom")); // "tomato tomato"
2. Extract unique values
By using the Set object and the spread operator, we can create a new array with only unique values.
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1] var unique_entries = [...new Set(entries)]; console.log(unique_entries); // [1, 2, 3, 4, 5, 6, 7, 8]
3. Convert number to string
We just need to connect a set of empty quotes.
var converted_number = 5 + ""; console.log(converted_number); // 5 console.log(typeof converted_number); // string
4. Convert string to number
All we need is operator.
One thing to note is that it only applies to "string numbers".
the_string = "123"; console.log(+the_string); // 123 the_string = "hello"; console.log(+the_string); // NaN
5. Randomly arrange the elements in the array
I shuffle the cards every day
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(my_list.sort(function() { return Math.random() - 0.5 })); // [4, 8, 2, 9, 1, 3, 6, 5, 7]
6. Multidimensional array flattening
Just use the spread operator.
var entries = [1, [2, 5], [6, 7], 9]; var flat_entries = [].concat(...entries); // [1, 2, 5, 6, 7, 9]
7. Short Circuit Condition
Let’s look at this example:
if (available) { addToCart(); }
Just use a variable with a function to shorten it :
available && addToCart()
8. Dynamic property names
I always thought that I must first declare an object before assigning dynamic properties.
const dynamic = 'flavour'; var item = { name: 'Coke', [dynamic]: 'Cherry' } console.log(item); // { name: "Coke", flavour: "Cherry" }
9. Use length to adjust or clear an array
We mainly rewrite the length of the array.
If we want to adjust the size of the array:
var entries = [1, 2, 3, 4, 5, 6, 7]; console.log(entries.length); // 7 entries.length = 4; console.log(entries.length); // 4 console.log(entries); // [1, 2, 3, 4]
If we want an empty array:
var entries = [1, 2, 3, 4, 5, 6, 7]; console.log(entries.length); // 7 entries.length = 0; console.log(entries.length); // 0 console.log(entries); // []
Recommended tutorial: "JS Tutorial"
The above is the detailed content of 9 powerful mainstream writing methods in JS (various Hack writing methods). For more information, please follow other related articles on the PHP Chinese website!