Arrays are everywhere in Javascript, and we can do a lot of cool things with the spread operator, a new feature in ECMAScript 6.
1. Iterate over an empty array
The array created directly in Javascript is loose, so that there will be many pitfalls. Try to create an array using the array constructor, and you’ll understand in no time.
const arr = new Array(4); [undefined, undefined, undefined, undefined] // [empty x 4] in Google Chrome
You will find it very difficult to loop through some transformations through a loose array.
const arr = new Array(4); arr. map((elem, index) => index); [undefined, undefined, undefined, undefined]
To fix this, you can use Array.apply when creating a new array.
const arr = Array.apply(null, new Array(4)); arr. map((elem, index) => index); [0, 1, 2, 3]
2. Pass an empty parameter to the method
If you want to call a method without filling in one of the parameters, Javascript will report an error.
method('parameter1', , 'parameter3'); // Uncaught SyntaxError: Unexpected token ,A common solution is to pass null or undefined.
method('parameter1', null, 'parameter3') // or method('parameter1', undefined, 'parameter3');According to the introduction of the spread operator in ES6, there is a more concise way to pass empty parameters passed to a method. As mentioned above, arrays are loose, so it's okay to pass null values to them, and we're taking advantage of this.
method(...['parameter1', , 'parameter3']); // code executed ...3. Array deduplication
I have never understood why the array does not provide a built-in function that allows us to easily get the value after deduplication. The spread operator helps us, using the spread operator with Set can generate a non-repeating array.
const arr = [...new Set([1, 2, 3, 3])]; // [1, 2, 3]4. Get array elements from back to front
If you want to get the elements of an array from the back to the front, you can write like this:
var arr = [ 1, 2, 3, 4] console. log(arr. slice(-1)) // [4] console. log(arr. slice(-2)) // [3, 4] console.log(arr.slice(-3)) // [2, 3, 4] console.log(arr.slice(-4)) // [1, 2, 3, 4]5. Short-circuit conditional sentence
If you want to execute a function when a conditional logic value is true, like this:
if (condition) { dosomething() }At this time, you can use short-circuit like this:
condition && dosomething()6. Use the operator "||" to set the default value
If you must To assign a default value to a variable, you can simply write it like this:
var a console.log(a) // undefined a = a || 'default value' console.log(a) // default value a = a || 'new value' console.log(a) // default value7. Use Object.is() in equality comparison
We all know that JavaScript is weakly typed, and when we use == for comparison, in some cases due to type conversion or "convert one of the two operands to the other, and then Compare", unexpected results will appear. Like this:
0 == ' ' //true null == undefined //true [1] == true //trueSo Javascript provides us with the equal operator ===, which is stricter than the inequal operator and does not cause type conversion. But using === for comparison is not the best solution. You may get:
NaN === NaN //falseES6 provides a new Object.is() method , which has some characteristics of ===, but is better and more precise, and performs well in some special cases:
Object.is(0 , & # 39; & # 39;); //false Object.is(null, undefined); //false Object.is([1], true); //false Object.is(NaN, NaN); //true8. Give a function Bind object
We often need to bind an object to the this of a method. In JS, if you want to call a function and specify its this you can use the bind method.
Bind Syntax
fun.bind(thisArg[, arg1[, arg2[, ... ]]])Parameters
thisArg
When the bound function is called, this parameter will be used as the this point of the original function.
arg1, arg2, …
When the bound function is called, these arguments will be passed to the bound method before the actual parameters.
Return value
Returns the copy of the original function modified by the specified this value and initialization parameters
Instance in JS
const myCar = { brand: 'Ford', type: 'Sedan', color: 'Red' }; const getBrand = function () { console.log(this.brand); }; const getType = function () { console.log(this.type); }; const getColor = function () { console.log(this.color); }; getBrand(); // object not bind, undefined getBrand(myCar); // object not bind, undefined getType.bind(myCar)(); // Sedan let boundGetColor = getColor.bind(myCar); boundGetColor(); // Red9. Get the file Extension
Solution 1: Regular Expression
function getFileExtension1(filename) { return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined; }Solution 2: Split method of String
function getFileExtension2(filename) { return filename.split('.').pop(); }These two solutions cannot solve some edge cases, there is another more powerful solution.
Solution 3: String slice, lastIndexOf method
function getFileExtension3(filename) { return filename. slice((filename. lastIndexOf(".") - 1 >>> 0) + 2); } console.log(getFileExtension3('')); // '' console.log(getFileExtension3('filename')); // '' console.log(getFileExtension3('filename.txt')); // 'txt' console.log(getFileExtension3('.hiddenfile')); // '' console.log(getFileExtension3('filename.with.many.dots.ext')); // 'ext'How is this achieved?
-
String.lastIndexOf() method Returns the position of the last occurrence of the specified value ('.' in this case) in the string in which the method was called, or -1 if not found.
-
The return value of lastIndexOf is 0 and -1 for 'filename' and '.hiddenfile' respectively unsigned right shift operator (»>) converts -1 to 4294967295 and -2 to 4294967294, this method keeps the filename unchanged in edge cases.
-
String.prototype.slice() Extracts the extension of the file at the index calculated above. If the index is greater than the length of the filename, the result is "".
10. Prevent unapply attacks
Rewrite the prototype method of the built-in object, and the external code can achieve the function of leaking and modifying the bound parameters by rewriting the code. This is a serious security issue when using polyfills under es5 methods.
// bind polyfill example function bind(fn) { var prev = Array.prototype.slice.call(arguments, 1); return function bound() { var curr = Array.prototype.slice.call(arguments, 0); var args = Array.prototype.concat.apply(prev, curr); return fn.apply(null, args); }; } // unapply attack function unapplyAttack() { var cOncat = Array.prototype.concat; Array.prototype.cOncat = function replaceAll() { Array.prototype.cOncat= concat; // restore the correct version var curr = Array.prototype.slice.call(arguments, 0); var result = concat. apply([], curr); return result; }; }
The above function declaration ignores the prev parameter of the function bind, which means that the first call to .concat after calling unapplyAttack will throw an error.
Using Object.freeze, you can make objects immutable, and you can prevent any built-in object prototype methods from being overridden.
(function freezePrototypes() { if (typeof Object. freeze !== 'function') { throw new Error(& # 39; Missing Object. freeze & # 39;); } Object. freeze(Object. prototype); Object. freeze(Array. prototype); Object. freeze(Function. prototype); }());
11. Javascript multidimensional array flattening
Here are three different ways to convert a multi-bit array into a single array.
var arr = [[1, 2],[3, 4, 5], [6, 7, 8, 9]];
Expected result:
[1, 2, 3, 4, 5, 6 , 7, 8, 9]
Solution 1: Use concat() and apply()
var newArr = [].concat.apply([], arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 2: Use reduce()
var newArr = arr.reduce(function(prev, curr) { return prev.concat(curr); }); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 3: Use the ES6 spread operator
var newArr = [].concat(...arr); console.log(newArr); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
12. How to use optional parameters in functions ( Including optional callback function)
The second and third parameters in the instance function are optional parameters
function example( err, optionA, optionB, callback ) { // Use an array to take out the arguments var args = new Array(arguments. length); for(var i = 0; i 0) optiOnA= args. shift(); else optiOnA= null; if (args. length > 0) optiOnB= args. shift(); else optiOnB= null; // continue as normal: check for errors if (err) { return callback && callback(err); } // print optional parameters console.log('optionA:', optionA); console.log('optionB:', optionB); console.log('callback:', callback); /* logic you want to do */ } // ES6 syntax is shorter function example(...args) { // The first parameter is an error parameter const err = args. shift(); // If the last parameter is a function, it is a callback function const callback = (typeof args[args. length-1] === 'function') ? args. pop() : null; // If there are still elements in args, that is the optional parameter you need You can take it out one by one like this: const optiOnA= (args. length > 0) ? args. shift() : null; const optiOnB= (args. length > 0) ? args. shift() : null; // ... repeat for more parameters if (err && callback) return callback(err); /* logic you want to do */ }
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Javascript skills. For more, please pay attention to other related articles on 1024programmer.com!
h:php;toolbar:false">var newArr = arr.reduce(function(prev, curr) {
return prev.concat(curr);
});
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 3: Use the ES6 spread operator
var newArr = [].concat(...arr); console.log(newArr); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
12. How to use optional parameters in functions ( Including optional callback function)
The second and third parameters in the instance function are optional parameters
function example( err, optionA, optionB, callback ) { // Use an array to take out the arguments var args = new Array(arguments. length); for(var i = 0; i 0) optiOnA= args. shift(); else optiOnA= null; if (args. length > 0) optiOnB= args. shift(); else optiOnB= null; // continue as normal: check for errors if (err) { return callback && callback(err); } // print optional parameters console.log('optionA:', optionA); console.log('optionB:', optionB); console.log('callback:', callback); /* logic you want to do */ } // ES6 syntax is shorter function example(...args) { // The first parameter is an error parameter const err = args. shift(); // If the last parameter is a function, it is a callback function const callback = (typeof args[args. length-1] === 'function') ? args. pop() : null; // If there are still elements in args, that is the optional parameter you need You can take it out one by one like this: const optiOnA= (args. length > 0) ? args. shift() : null; const optiOnB= (args. length > 0) ? args. shift() : null; // ... repeat for more parameters if (err && callback) return callback(err); /* logic you want to do */ }
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Javascript skills. For more, please pay attention to other related articles on 1024programmer.com!