The Hacker method is a build method that continually improves and iterates. Programmers with a hacker spirit believe that there is always room for improvement and that nothing is perfect. Each piece of code has room for further refinement, and each operation has a more convenient technique.
Here are some very powerful JavaScript hacks.
1. Replace All
We know that string.replace () only replaces the first item.
You can replace everything with /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"
Copy the code
2. Extract unique values
We can use the Set object and the Spread operator to create a new array that strips out duplicate 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]
Copy the code
3. Convert numbers to strings
We simply use the concatenation operator with empty quotes.
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string
Copy the code
4. Convert strings to numbers
Use the + operator.
Note the usage here, as it only applies to “string numbers”.
the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaN
Copy the code
5. Randomly arrange the elements in the array
Every day I’m lining up at random…
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. Flattening a multidimensional array simply uses the Spread operator. var entries = [1, [2, 5], [6, 7], 9]; var flat_entries = [].concat(... entries); // [1, 2, 5, 6, 7, 9]Copy the code
7. Short circuit conditions
Here’s an example:
if (available) { addToCart(); } Just use variables and functions to shorten it: available && addToCart()Copy the code
8. Dynamic property names
I always thought I had to declare an object before I could assign a dynamic property.
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }
Copy the code
9. Use length to resize/empty the array
It basically overrides the length of the array.
If we want to resize 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]
Copy the code
If we want to empty the 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); / / []Copy the code
If you’re also looking for JavaScript hacker tips, I hope you found this article helpful.