A lot of useful things in "go" javascript

Source: Internet
Author: User
Tags anonymous collator intl string format unique id hasownproperty mozilla developer network



Original: https://www.cnblogs.com/ys-ys/p/5158510.html



--------------------------------------------------------------------------------



Thank you for this good article from the Broken Wolf, as well as the authors who wrote these points of knowledge and put them together. This is an article on GitHub, here the beast is only to do translation, because the animal English proficiency and programming skills are not good, if there are bad places also please understand more understanding. Poke here: Original



It's a pleasure for me to be able to provide you with these short and useful javascript tricks to improve your programming skills. In less than 2 minutes per day, you will be able to read the features that the dreaded language of JavaScript presents to US: performance (performance), Conventions (protocol), hacks (code hack), interview Questions (interview questions) and all the other stuff.



Second address: (translation, continuous updating) JavaScript Tips (ii)



The third address: (translation, continuous updating) JavaScript Tips (iii)



Fourth. Address: (translation, continuous updating) JavaScript Tips (iv)



#15-Use a simpler indexof-like method of inclusion judgment
Native JavaScript does not have a contains method. You can do this for checking whether a value exists in a string or string array item:


var sometext = ' JavaScript rules '; if (
var someText = ‘JavaScript rules‘;
if (someText.indexOf(‘JavaScript‘) !== -1) {
}
// or
if (someText.indexOf(‘JavaScript‘) >= 0) {
}
.indexof (' JavaScript ')!==-1) {}//or if (Sometext.indexof (' JavaScript ') &G t;= 0) {}


But let's look at these EXPRESSJS code snippets again.


// examples/mvc/lib/boot.js
for (var key in obj) {
  // "reserved" exports
  if (~[‘name‘, ‘prefix‘, ‘engine‘, ‘before‘].indexOf(key)) continue;

// examples/lib/utils.js
exports.normalizeType = function(type){
  return ~type.indexOf(‘/‘)
    ? acceptParams(type)
    : { value: mime.lookup(type), params: {} };
};

// examples/web-service/index.js
// key is invalid
if (!~apiKeys.indexOf(key)) return next(error(401, ‘invalid api key‘));


The problem is the ~ bit operator. The operator performs binary expressions such as operations, but they return the numeric value of the standard JavaScript.
They convert 1 to 0, and 0 is false in JavaScript.


var someText = ‘text’;
!! ~ someText.indexOf (‘tex‘); // someText contains "tex"-true
! ~ someText.indexOf (‘tex‘); // someText does not contain "tex"-false
~ someText.indexOf (‘asd’); // someText does not contain "asd"-false
~ someText.indexOf (‘ext‘); // someText contains "ext"-true

String.prototype.includes ()


The includes () method that is described in ES6 (ES 2015) can be used to determine whether a string contains another string:


' Something '. Includes (' thing '); True


In ECMAScript (ES7), even arrays can do this, such as indexof:


!!~[1, 2, 3].indexOf(1); // true
[1, 2, 3].includes(1); // true


Unfortunately, this is only supported in browsers with Chrome,firefox,safari 9 or more.



#14-arrow function (ES6)
Introducing the new features in ES6, the arrow function can be a handy tool for writing more code with fewer lines. His name comes from his grammar,=> and the little arrow-like a "chubby arrow". Some people may know that this type of function and other static languages such as lambda expressions are anonymous functions. It is called anonymous because these arrow functions do not have a descriptive function name.
So what's good about that?
Syntax: less loc, without typing the function keyword over and over again.
Semantic: Captures the keyword from context this.
Simple syntax Case:
Take a look at the following two snippets of code, and they do the same job. You can quickly understand the function of the arrow function.


// arrow function's daily syntax
param => expression
// may also be written in parentheses
// parentheses are multi-parameter requirements
(param1 [, param2]) => expression

// use everyday functions
var arr = [5,3,2,9,1];
var arrFunc = arr.map (function (x) {
   return x * x;
});
console.log (arr)

// use arrow function
var arr = [5,3,2,9,1];
var arrFunc = arr.map ((x) => x * x);
console.log (arr)


As you can see, the arrow function in this example saves you the time of entering parentheses within the parameters and returning the keywords. It is recommended that the parameters in parentheses be entered, such as (x, y) = X+y. In a different use case, it's just



A way to deal with oblivion. But the code above will do the same: x = X*x. For now, these are just syntactic improvements that lead to less LOC and better readability.
This binding
There is a better reason to use the arrow function. That is, in the context of this issue. With the arrow function, you don't have to worry about. Bind (this) and that=this. Because the arrow function finds this from the context.



Look at the following example:


// define this.i globally
this.i = 100;
var counterA = new CounterA ();
var counterB = new CounterB ();
var counterC = new CounterC ();
var counterD = new CounterD ();

// bad example
function CounterA () {
  // CounterA ‘s `this` instance (!! Ignore this)
  this.i = 0;
  setInterval (function () {
    // `this` refers to the global object, not CounterA ’s` this`
    // So start counting with 100 instead of 0 (local this.i)
    this.i ++;
    document.getElementById ("counterA"). innerHTML = this.i;
  }, 500);
}
// manually bind that = this
function CounterB () {
  this.i = 0;
  var that = this;
  setInterval (function () {
    that.i ++;
    document.getElementById ("counterB"). innerHTML = that.i;
  }, 500);
}
// use .bind (this)
function CounterC () {
  this.i = 0;
  setInterval (function () {
    this.i ++;
    document.getElementById ("counterC"). innerHTML = this.i;
  } .bind (this), 500);
}
// use arrow function
function CounterD () {
  this.i = 0;
  setInterval (() => {
    this.i ++;
    document.getElementById ("counterD"). innerHTML = this.i;
  }, 500);
}


Further information about the arrow function can be seen here. To view the different syntax options, visit the site.



#13-Tips for measuring the performance of a JavaScript code block
To quickly measure the performance of a JavaScript block, we can use the functions of the console like Console.time (label) and Console.timeend (label)


console.time("Array initialize");
var arr = new Array(100),
    len = arr.length,
    i;
for (i = 0; i < len; i++) {
    arr[i] = new Object();
};
console.timeEnd("Array initialize"); // output: Array initialize: 0.711ms


More information Console object, JavaScript Benchmarking
Demo:jsfiddle-codepen (in browser console output)



Parameter processing in #12-ES6
In many programming languages, the parameters of the function are default, and the developer must explicitly define a parameter that is optional. Each parameter in JavaScript is optional, but we can do this without having a function take advantage of the default value of ES6 as a parameter.


const _err = function( message ){
  throw new Error( message );
}
const getSum = (a = _err(‘a is not defined‘), b = _err(‘b is not defined‘)) => a + b
getSum( 10 ) // throws Error, b is not defined
getSum( undefined, 10 ) // throws Error, a is not defined


_err is a function that throws an error immediately. If there is not a parameter as the value, the default value is used, _err will be called and an error will be thrown. More examples of default parameters you can see on the Mozilla Developer Network.



#11-Lifting
Understanding Ascension will help you organize your function. Just remember that variable declarations and definition functions are promoted to the top. The definition of a variable is not, even if you declare and define a variable on the same line. In addition, a variable declaration lets the system know that a variable exists, and the definition assigns it to it.


function doTheThing () {
   // error: notDeclared is not defined
   console.log (notDeclared);
   // Output: undefined
   console.log (definedLater);
   var definedLater;
   definedLater = ‘I am defined!’
   // Output: ‘I am defined!’
   console.log (definedLater)
   // Output: undefined
   console.log (definedSimulateneously);
   var definedSimulateneously = ‘I am defined!’
   // Output: ‘I am defined!’
   console.log (definedSimulateneously)
   // Output: ‘I did it!’
   doSomethingElse ();
   function doSomethingElse () {
     console.log (‘I did it!’);
   }
   // error: undefined is not a function
   functionVar ();
   var functionVar = function () {
     console.log (‘I did it!’);
   }
}


To make things easier to read, raising the declaration of a variable within the scope of a function will let you make sure which scope the declaration of the variable comes from. Define them before you need to use the variables. Define functions at the bottom of the scope to ensure that the code is clear and prescriptive.



#10-Checks whether an object has properties
When you want to check whether an object has a property, you might do this:


var myObject = {
  name: ‘@tips_js‘
};
if (myObject.name) { ... }


It's okay, but you have to know that there are two native ways, in operator and Object.hasownproperty, each object is an object, both methods are available. Each object inherits from object, and both methods are available.
Some of the different points of the two methods:


var myObject = {
   name: ‘@tips_js’
};
myObject.hasOwnProperty (‘name’); // true
‘Name’ in myObject; // true
myObject.hasOwnProperty (‘valueOf‘); // false, valueOf is inherited from the prototype chain
‘ValueOf’ in myObject; // true


The difference between them is the nature of the check, in other words, when the object itself has a lookup property, hasOwnProperty Returns True, however, in operator does not differentiate between the object created by the property and the inherited prototype chain of the property.
Here's another example:


var myFunc = function () {
   this.name = ‘@tips_js’;
};
myFunc.prototype.age = ‘10 days ’;
var user = new myFunc ();
user.hasOwnProperty (‘name’); // true
user.hasOwnProperty (‘age‘); // false, because age is on the prototype chain


Click to see an example. At the same time, it is recommended that you read these common errors when checking the existence of an object's properties.



#09-Template string
As of Es6,js, there is already a template string as an alternative to the classic string reference.
Case: Normal string


var firstName = ‘Jake‘;
var lastName = ‘Rawr‘;
console.log(‘My name is ‘ + firstName + ‘ ‘ + lastName);
// My name is Jake Rawr


Template string:


var firstName = ‘Jake‘;
var lastName = ‘Rawr‘;
console.log(`My name is ${firstName} ${lastName}`);
// My name is Jake Rawr


In the template string ${}, you can implement multi-line strings without writing/n or simple logic.
You can also use functions to modify the output of template strings, which are called tags of template strings. You may also want to read more about understanding template strings.



#08-Convert the node list to an array
The Queryselectorall method returns an array of similar node list objects. These data structures are similar to arrays, because they often appear as arrays, but they cannot be used in arrays, such as maps and foreach. Here's a quick, safe, reusable way to list a node to an array of DOM elements:


const nodelist = document.querySelectorAll(‘div‘);
const nodelistToArray = Array.apply(null, nodelist);
//later on ..
nodelistToArray.forEach(...);
nodelistToArray.map(...);
nodelistToArray.slice(...);
//etc...


The Apply method is to pass a series of array-formatted parameters to a function given this. The MDN states that apply will invoke an array-like object, which is what Queryselectorall returns. Because we don't need to specify this in the context of the function, we pass in null or 0. The returned result is a set of DOM element arrays that can use array methods.



If you are using es2015 you can take advantage of ... (spread operator)


const nodelist = [... document.querySelectorAll (‘div’)]; // returns a real array
// later on ..
nodelist.forEach (...);
nodelist.map (...);
nodelist.slice (...);
// etc ...


#07-"Use strict" and "lazy"
Strict mode makes it more secure for developers to write JavaScript.
By default, JavaScript allows developers to be lazy, for example, when we declare a variable for the first time without Var, although this may seem like an inexperienced developer, and this is the source of many errors, the variable name is misspelled or accidentally referred to an external scope.



Programmers like to let computers do boring things for us, such as checking out some of our mistakes in our work. The "use strict" instruction will help us do these error checks and convert our errors to JavaScript errors.
We put this command by adding the top of a JS file:


// The entire script file will be in strict mode syntax
"use strict";
var v = "Hi! I ‘m a strict mode script!";
Or inside a function:
function f ()
{
// strict mode syntax in function scope
   ‘Use strict’;
   function nested () {return "And so am I!";}
   return "Hi! I ‘m a strict mode function!" + nested ();
}
function f2 () {return "I ‘m not strict.";}


Within the JavaScript file or function that contains this instruction, we disable the bad behavior in some of the larger JavaScript projects directly in the JavaScript engine execution. In other cases, strict mode changes the following behavior:
· Variables are only declared in front of Var to be used
· Error attempting to write read-only property
· constructor must be called with the new keyword
· This does not point to the global object by default
· Very limited use of eval ()
· Protect reserved characters or future reserved characters from being used as variable names
Strict mode is good for new projects, but it is very challenging to use it in the old projects where it is not used in most places. When you merge multiple files into a file, it is also a problem, as if the entire file is being executed in strict mode.
It is not a declaration, just a literal, and the earlier version of the browser ignores it. Strict mode support:
· IE + +
· FF 4+
· Chrome 13+
· Safari 5.1+
· Opera 12+
See MDN for Strict mode descriptions.



#06-a method that processes an array or a single element as a parameter
Rather than writing a separate method to manipulate an array and an element as a function of parameters, it is better to write a generic function so that it can be manipulated. This is similar to some of the jquery methods (CSS matching will modify all selectors).
You just need to put everything in the array first, ARRAY.CONCAT will receive an array or a single object:


function printUpperCase(words) {
  var elements = [].concat(words);
  for (var i = 0; i < elements.length; i++) {
    console.log(elements[i].toUpperCase());
  }
}


Printuppercase can now receive either a single element as an argument or an array:


printUpperCase("cactus");
// => CACTUS
printUpperCase(["cactus", "bear", "potato"]);
// => CACTUS
//  BEAR
//  POTATO


#05-undefined and Null are different
· Undefined refers to a variable that is not declared, or that a variable is declared but not assigned a value
· Null refers to a specific value, that is, "no value"
. JavaScript defines unassigned variables by default as undefined
· JavaScript does not set a null value for an unassigned variable, which is used by programmers to represent a worthless value
· Undefined is not valid in JSON format data, and NULL is valid
· Undefined type is undefined
· Null is similar to object. Why?
· Both are primitive values
· Both are considered false (Boolean (undefined)//False, Boolean (NULL)//False).
· Identify the variable is not undefined


typeof variable = = = "undefined"


· Check if the variable is not NULL


Variable = = = "Null"


Consider them to be equal from values, but consider them as unequal from type and value


NULL = = undefined//Truenull = = undefined//False


#04-sorting strings in non-ASCII character form
JavaScript has a native way of sorting arrays in string format, and making a simple array.sort () will arrange strings in alphabetical order. Of course, you can also provide a custom sort feature.


[‘Shanghai‘, ‘New York‘, ‘Mumbai‘, ‘Buenos Aires‘].sort();
// ["Buenos Aires", "Mumbai", "New York", "Shanghai"]


When you try to sort by using non-ASCII characters such as [' É ', ' a ', ' ú ', ' C '], you get a strange result [' C ', ' e ', ' á ', ' ú '] because only the English language can sort, so this happens.
See a simple example:


// Spanish
[‘Único’, ‘árbol’, ‘cosas’, ‘fútbol’]. Sort ();
// ["cosas", "fútbol", "árbol", "único"] // wrong order
// German
[‘Woche’, ‘w? Chentlich’, ‘w? Re’, ‘Wann’]. Sort ();
// ["Wann", "Woche", "w? Re", "w? Chentlich"] // Wrong order


Fortunately, there are two ways to avoid this behavior, and the Internationalized ECMAScript API provides Localecompare and and Intl.collator.
Both of these methods have their own custom parameters, so that they can be configured to fully complete the functionality.
Using Localecompare ()


[‘único‘,‘árbol‘, ‘cosas‘, ‘fútbol‘].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["árbol", "cosas", "fútbol", "único"]
[‘Woche‘, ‘w?chentlich‘, ‘w?re‘, ‘Wann‘].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["Wann", "w?re", "Woche", "w?chentlich"]


Using Intl.collator ()


[‘único‘,‘árbol‘, ‘cosas‘, ‘fútbol‘].sort(Intl.Collator().compare);
// ["árbol", "cosas", "fútbol", "único"]
[‘Woche‘, ‘w?chentlich‘, ‘w?re‘, ‘Wann‘].sort(Intl.Collator().compare);
// ["Wann", "w?re", "Woche", "w?chentlich"]


· Each method can customize the location
· In the FF browser, Intl.collator () will be faster when compared to a larger number or string
Therefore, when you assign a value to a string array in a language other than English, remember to use this method to avoid accidental sorting.



#03-Improve nesting conditions
How can we improve and make more efficient nesting of if statements in JavaScript.


if (color) {
  if (color === ‘black‘) {
    printBlackBackground();
  } else if (color === ‘red‘) {
    printRedBackground();
  } else if (color === ‘blue‘) {
    printBlueBackground();
  } else if (color === ‘green‘) {
    printGreenBackground();
  } else {
    printYellowBackground();
  }
}


An improved approach is to replace nested IF statements with a switch statement. Although the code is more concise and orderly, it is not recommended because it is difficult to debug. The reason is pointed out here.


switch(color) {
  case ‘black‘:
    printBlackBackground();
    break;
  case ‘red‘:
    printRedBackground();
    break;
  case ‘blue‘:
    printBlueBackground();
    break;
  case ‘green‘:
    printGreenBackground();
    break;
  default:
    printYellowBackground();
}


But when we have more than one condition to judge? In this case, if we want to make the code more concise and orderly, we can use switch. If we pass true as a parameter to the switch statement, it allows us to place a condition in each case.


switch(true) {
  case (typeof color === ‘string‘ && color === ‘black‘):
    printBlackBackground();
    break;
  case (typeof color === ‘string‘ && color === ‘red‘):
    printRedBackground();
    break;
  case (typeof color === ‘string‘ && color === ‘blue‘):
    printBlueBackground();
    break;
  case (typeof color === ‘string‘ && color === ‘green‘):
    printGreenBackground();
    break;
  case (typeof color === ‘string‘ && color === ‘yellow‘):
    printYellowBackground();
    break;
}


But we have to avoid multiple checks under each condition and try to avoid using switch. We also have to take into account that the most effective way is through an object.


var colorObj = {
  ‘black‘: printBlackBackground,
  ‘red‘: printRedBackground,
  ‘blue‘: printBlueBackground,
  ‘green‘: printGreenBackground,
  ‘yellow‘: printYellowBackground
};

if (color in colorObj) {
  colorObj[color]();
}


There is more information about this.



It is important to #02 the keys of the-reactjs sub-structure.
Keys is a property that represents all the components that you need to pass to a dynamic array. This is a unique and specified id,react used to identify each DOM component to be used to know that it is a different component or the same component. Use keys to ensure that subcomponents are saved and not created again, and to prevent the creation of weird things.
· Use a separate object value that already exists
· To define a key in the parent component, not a child component


//not good
...
render () {
     <div key = {{item.key}}> {{item.name}} </ div>
}
...
//Ok
<MyComponent key = ({item.key}} />


· Using arrays is not a good habit
· Random () never executes


Bad <mycomponent key={{math.random ()}}/>


· You can create your unique ID, make sure that the method is fast and already attached to the object
· When the number of children is large or contains complex components, use keys to improve performance
· You must provide the key attribute for all child reactcsstransitiongroup



#01-angularjs: $digest vs $apply
One of the most appreciated features of ANGULARJS is bidirectional data binding. In order for it to work, ANGULARJS evaluates the change of the model and the cycle of the View ($digest). You need to understand this concept in order to understand how the framework works in the engine.
Angular evaluates the change in each event at each time. This is the $digest cycle. Sometimes you have to trigger a new loop manually, and you have to have the right choice, because this stage is the most influential performance aspect.
$apply
This core approach allows you to start a $digest loop. This means that all the objects in the Watch list are checked, and the entire application launches the $digest loop. Internally, after executing the optional function arguments, call $rootscope. $digest ();
$digest
In this case, the $digest method executes at the current scope and its child scope, and you should notice that the scope of the parent is not checked and is not affected.
Suggestions:
· Use $apply or $digest only when the browser DOM event is triggered outside of angular
· To pass a function expression to $apply, there is an error handling mechanism: Allows the integration of changes in the digest cycle.


$scope.$apply(() => {
    $scope.tip = ‘Javascript Tip‘;
});


· If you just want to update the current scope or his child scope, use $digest and prevent the $digest of the entire application. Performance is self-evident.
· When $apply has a lot of stuff tied up, it's a tough process for machines that can cause performance problems.
·  If you are using angular 1.2.x or above, use $evalasync. This is a core method of evaluating an expression during the current or next cycle, which can improve the performance of your application.



#00-Inserts an item in an array



Inserting an element into an existing array is a common task, and you can use push to add elements to the end of the array, use Unshift at the beginning, or use splice.



These are known methods, but this does not mean that there is no higher performance implementation.



Adding an element at the end of the array is easy with push (), but there is a higher-performance approach.


var arr = [1,2,3,4,5];
arr.push (6); // Improved speed by about 50% on Chrome (window 7)
arr [arr.length] = 6; // 43% speed improvement on Chrome 47.0.2526.106 (Mac OS X 10.11.1)


Both of these methods modify the array, do not believe? Look at this jsperf.
Now, if we're trying to add an item to the beginning of the array:


var arr = [1,2,3,4,5];
arr.unshift (0); // Improved speed by about 15% on Chrome (window 7)
[0] .concat (arr); // 98% speed improvement on Chrome 47.0.2526.106 (Mac OS X 10.11.1)


Here is a bit more detailed: Unshift edits the original array, CONCAT returns a new array. Jsperf
Adding items in the array is easy to use splice, which is the most efficient way to do it.


var items = [‘one‘, ‘two‘, ‘three‘, ‘four‘];
items.splice(items.length / 2, 0, ‘hello‘);


# # 2016-01-25 Update # # #



Not to be continued ... (This article knowledge points such as in GitHub has the update, this side every little time also will do the corresponding update, forgives the beast time is not so sufficient)



This article will also be published in the number "Shuang_lang_shuo", at the same time we also support the new book "Angularjs depth Analysis and best practice."



A lot of useful things in "go" javascript


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.