A comprehensive introduction to javascript practical skills and single vertical bars and javascript Practical Skills

Source: Internet
Author: User

A comprehensive introduction to javascript practical skills and single vertical bars and javascript Practical Skills

JavaScript itself can be regarded as a simple language, but we are constantly improving it with wisdom and flexibility. Yesterday we applied these patterns to JavaScript frameworks. Today these frameworks drive our Web applications. Many new developers are attracted by a variety of powerful JavaScript frameworks, but they ignore the JavaScript practical skills behind the framework. This article will give you a comprehensive introduction to the knowledge points.

I. js integer operations

Use | 0 and ~~ The floating point can be converted into an integer and the efficiency is faster than the similar parseInt and Math. round, which is useful in processing pixel and animation displacement effects. See this for performance comparison.

Var foo = (12.4/4.13) | 0; // The result is 3var bar = ~~ (12.4/4.13); // The result is 3.

Another trick is !! Two exclamation marks, one value, can be quickly converted to a Boolean value. You can test it!

var eee="eee";alert(!!eee)

The return value is true, that is, the value is added before any value !! Can always be equal to true. Unless this value is a Boolean value, or it is undefined, null, 0, false, NaN, '', Because I mentioned undefined, null, 0, false, NaN ,'', these are actually false, so we added two !! And then fasle.

2. Rewrite native alert to record the number of pop-up boxes

(function() { var oldAlert = window.alert, count = 0; window.alert = function(a) { count++; oldAlert(a + "\n You've called alert " + count + " times now. Stop, it's evil!"); };})();alert("Hello Haorooms");

Iii. Method for digital exchange not declaring intermediate Variables

When we exchange two numbers, we generally declare an intermediate variable, but today's practice is amazing. You don't need to declare the intermediate variable to see how it is implemented!

Var a = 1, B = 2; a = [B, B = a] [0]; console. log ('a: '+ a +', B: '+ B); // Output a: 2, B: 1

How is this method a new look?

4. All objects

In the JavaScript world, everything is an object. Except null and undefined, other basic types of numbers, strings, and boolean values all have pairs that should be wrapped. One feature of an object is that you can call methods directly on it.

For the basic numeric type, if you try to call the toString Method on it, it will fail, but the call will not fail if it is enclosed in parentheses, the internal implementation is to convert the basic type into an object with the corresponding packaging object. So (1). toString () is equivalent to new Number (1). toString (). Therefore, you can use basic types of numbers, strings, and boolean as objects, but pay attention to proper syntax.

At the same time, we noticed that the numbers in JavaScript are non-floating-point and integer. All numbers are actually floating-point, but the decimal point is omitted. For example, you can write 1 as 1 ., that's why when you try. when toString () is used, an error is reported, so the correct format should be as follows: 1 .. toString (), or add parentheses as described above. Here, brackets are used to correct the JS parser. Do not treat the dot after 1 as the decimal point. As described above, the internal implementation is to convert 1. Wrap the object into an object and then call the method.

5. If statement Deformation

When you need to write an if statement, try another simpler method, instead of using the logical operators in JavaScript.

Var day = (new Date). getDay () = 0; // traditional if statement if (day) {alert ('Today is Sunday! ') ;}; // Use the logic and replace ifday & alert ('Today is Sunday! ');

For example, the above Code first obtains the date of today. If it is Sunday, a window pops up. Otherwise, nothing will be done. We know that there is a short circuit in the logical operation. For the logic and expression, the result is true only when both are true. If the previous day variable is determined to be false, the result is false for the entire expression, so it will not continue to execute the subsequent alert. If the previous day is true, continue to execute the following code to determine whether the entire expression is true or false. This achieves the if effect.

For traditional if statements, if the execution body Code contains more than one statement, curly brackets are required. Using a comma expression, you can execute any code without curly brackets.

if(conditoin) alert(1),alert(2),console.log(3);

6. Use = instead of =

= (Or! =) The operator automatically performs type conversion when needed. = (Or! =) The operation will not perform any conversions. It compares values and types and is considered to be faster than =.

[10] === 10 // is false[10] == 10 // is true'10' == 10 // is true'10' === 10 // is false [] == 0 // is true [] === 0 // is false '' == false // is true but true == "a" is false '' === false // is false

7. Use closures to implement private variables

Function Person (name, age) {this. getName = function () {return name;}; this. setName = function (newName) {name = newName;}; this. getAge = function () {return age ;}; this. setAge = function (newAge) {age = newAge ;}; // The property var occupation that is not initialized in the constructor; this. getOccupation = function () {return occupation ;}; this. setOccupation = function (newOcc) {occupation = newOcc ;};}

8. Create object constructor

function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName;}var Saad = new Person("Saad", "Mousliki");


9. Use typeof, instanceof, and constructor with caution.

var arr = ["a", "b", "c"];typeof arr; // return "object"arr instanceof Array // truearr.constructor(); //[]

10. Create a Self-called function (Self-calling Funtion)

This is often called Self-Invoked Anonymous Function or the IIFE-Immediately Invoked Function Expression ). This is a function that is automatically executed immediately after creation, usually as follows:

(function(){ // some private code that will be executed automatically})();(function(a,b){ var result = a+b; return result;})(10,20)

11. Obtain a random entry from the array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];var randomItem = items[Math.floor(Math.random() * items.length)];

12. Obtain a random number within a specific range

This code snippet is useful when you want to generate test data, such as a random salary value between the minimum and maximum values.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

13. generate an array of numbers between 0 and the set maximum.

var numbersArray = [] , max = 100;for( var i=1; numbersArray.push(i++) < max;); // numbers = [0,1,2,3 ... 100]

14. Generate a random alphanumeric string

Function generateRandomAlphaNum (len) {var rdmstring = ""; for (; rdmString. length <len; rdmString + = Math. random (). toString (36 ). substr (2); return rdmString. substr (0, len);} // call the method generateRandomAlphaNum (15 );

15. Disrupt a number Array

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];numbers = numbers.sort(function(){ return Math.random() - 0.5});/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205] */

16. trim function of String

String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};

17. append an array to another Array

var array1 = [12 , "foo" , {name: "Joe"} , -2458];var array2 = ["Doe" , 555 , 100];Array.prototype.push.apply(array1, array2);/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

18. Convert the arguments object into an array

Var argArray = Array. prototype. slice. call (arguments); [Note: the arguments object is a class Array object, but not a real Array]

19. verify whether the parameter is a number)

function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n);}

20. verify whether the parameter is an array.

function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ;}

Note: If the toString () method is overwritten (overridden), you will not be able to get the desired result by using this technique. Or you can use:

Array. isArray (obj); // This is a new array method.

If you do not use multiple frames, you can also use the instanceof method. However, if you have multiple contexts, you will get the wrong result.

var myFrame = document.createElement('iframe');document.body.appendChild(myFrame);var myArray = window.frames[window.frames.length-1].Array;var arr = new myArray(a,b,10); // [a,b,10]// instanceof will not work correctly, myArray loses his constructor// constructor is not shared between framesarr instanceof Array; // false

[Translator's note: There are many discussions on how to judge the array on the Internet. You can google it. This article is quite detailed .]

21. obtain the maximum or minimum values in a number array.

Var numbers = [5,458,120,-215,228,400,122 205,-85411];
Var maxInNumbers = Math. max. apply (Math, numbers );
Var minInNumbers = Math. min. apply (Math, numbers );
Note: The Function. prototype. apply method is used to pass parameters]

22. Clear an array

var myArray = [12 , 222 , 1000 ];myArray.length = 0; // myArray will be equal to [].

23. Do not use delete to delete items in an array.

Use splice instead of delete to delete an item in the array. Delete is used to replace the original items with undefined instead of deleting them from the array.

Do not use this method:

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];items.length; // return 11delete items[3]; // return trueitems.length; // return 11/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

And use:

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];items.length; // return 11items.splice(3,1) ;items.length; // return 10/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

The delete method should be used to delete an attribute of an object.

Twenty-four. Use length to truncate an array.

Similar to the preceding method of clearing an array, we use the length attribute to truncate an array.

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

In addition, if you set the length of an array to a value greater than the current value, the length of the array will be changed and a new undefined item will be added. The length of an array is not a read-only attribute.

myArray.length = 10; // the new array length is 10myArray[myArray.length - 1] ; // undefined

25. Use logic AND/OR for conditional judgment

Same as (5). if deformation statement!

Var foo = 10; foo = 10 & doSomething (); // equivalent to if (foo = 10) doSomething (); foo = 5 | doSomething (); // equivalent to if (foo! = 5) doSomething ();


Logical AND can also be used to set default values for function parameters

Function doSomething (arg1) {Arg1 = arg1 | 10; // If arg1 is not set, Arg1 is set to 10 by default}

26. Use the map () method to traverse items in an array

var squares = [1,2,3,4].map(function (val) { return val * val;});// squares will be equal to [1, 4, 9, 16]

27. Rounding a number to keep N decimal places

var num =2.443242342;num = num.toFixed(4); // num will be equal to 2.4432

Floating Point

0.1 + 0.2 === 0.3 // is false9007199254740992 + 1 // is equal to 90071992547409929007199254740992 + 2 // is equal to 9007199254740994

Why? 0.1 + 0.2 equals 0.30000000000000004. You need to know that all JavaScript numbers are internally represented by 64-bit binary floating point numbers, which comply with the IEEE 754 standard. For more information, read this blog. You can use toFixed () and toPrecision () methods to solve this problem.

29. Check the attributes when you use for-in to traverse the internal attributes of an object.

The following code snippet can avoid accessing the prototype attributes when traversing an object attribute.

for (var name in object) { if (object.hasOwnProperty(name)) { // do something with name }}

Thirty, comma Operator

var a = 0;var b = ( a++, 99 );console.log(a); // a will be equal to 1console.log(b); // b is equal to 99

. Cache variables that need to be calculated and queried (calculation or querying)

For jQuery selectors, we 'd better cache these DOM elements.

var navright = document.querySelector('#right');var navleft = document.querySelector('#left');var navup = document.querySelector('#up');var navdown = document.querySelector('#down');

. Verify the parameter before calling isFinite ()

isFinite(0/0) ; // falseisFinite("foo"); // falseisFinite("10"); // trueisFinite(10); // trueisFinite(undifined); // falseisFinite(); // falseisFinite(null); // true !!!

33. Avoid the negative index (negative indexes) in the array)

var numbersArray = [1,2,3,4,5];var from = numbersArray.indexOf("foo") ; // from is equal to -1numbersArray.splice(from,2); // will return [5]

Make sure that the parameters when indexOf is called are not negative.

34. JSON-based serialization and deserialization (serialization and deserialization)

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };var stringFromPerson = JSON.stringify(person);/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */var personFromString = JSON.parse(stringFromPerson);/* personFromString is equal to person object */

35. Avoid using eval () and Function Constructors

Using eval and Function constructor is very expensive because every time they call the script engine to convert source code into executable code.

var func1 = new Function(functionCode);var func2 = eval(functionCode);

36. Avoid using ()

With (), a global variable is inserted. Therefore, variables with the same name will be overwritten, causing unnecessary trouble.

37. Avoid using for-in to traverse an array.

Avoid using this method:

var sum = 0;for (var i in arrayNumbers) { sum += arrayNumbers[i];}

The better way is:

var sum = 0;for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i];}

The additional benefit is that the values of the I and len variables are executed only once, which is more efficient than the following method:

for (var i = 0; i < arrayNumbers.length; i++)

Why? Because arrayNumbers. length is calculated every time it is cyclically.

When setTimeout () and setInterval () are called, the function is passed in, instead of a string.

If you pass the string to setTimeout () or setInterval (), the string will be parsed like eval, which is very time-consuming.

Do not use:

setInterval('doSomethingPeriodically()', 1000);setTimeOut('doSomethingAfterFiveSeconds()', 5000)

Usage:

setInterval(doSomethingPeriodically, 1000);setTimeOut(doSomethingAfterFiveSeconds, 5000);

39. Use the switch/case statement instead of a long string of if/else

When there are more than two conditions, the use of switch/case is more efficient and more elegant (easier to organize code ). However, do not use switch/case when there are more than 10 cases.

40. Use switch/case when determining the value range

In the following case, it is reasonable to use switch/case to determine the value range:

function getCategory(age) { var category = ""; switch (true) { case isNaN(age):  category = "not an age";  break; case (age >= 50):  category = "Old";  break; case (age <= 20):  category = "Baby";  break; default:  category = "Young";  break; }; return category;}getCategory(5); // will return "Baby"

[Translator's note: It is generally appropriate to use if/else To determine the value range. Switch/case is more suitable for determining the value]

. Specify the prototype object for the created object

It is possible to write a function to create an object with the specified parameter as prototype:

function clone(object) { function OneShotConstructor(){}; OneShotConstructor.prototype= object; return new OneShotConstructor();}clone(Array).prototype ; // []

Forty-two, an HTML Escape Function

function escapeHTML(text) { var replacements= {"<": "<", ">": ">","&": "&", "\"": """}; return text.replace(/[<>&"]/g, function(character) { return replacements[character]; });}

Forty-three, avoid using try-catch-finally inside the loop

During runtime, when the catch clause is executed, the caught exception object is assigned a variable, and this variable is created every time in the try-catch-finally structure.

Avoid writing like this:

var object = ['foo', 'bar'], i;for (i = 0, len = object.length; i <len; i++) { try { // do something that throws an exception } catch (e) { // handle exception }}

And use:

var object = ['foo', 'bar'], i;try { for (i = 0, len = object.length; i <len; i++) { // do something that throws an exception }}catch (e) { // handle exception}

Forty-four. set timeout for XMLHttpRequests.

After an XHR request takes a long time (for example, due to network problems), you may need to abort this request, so you can use setTimeout () for XHR calls ().

var xhr = new XMLHttpRequest ();xhr.onreadystatechange = function () { if (this.readyState == 4) { clearTimeout(timeout); // do something with response data }}var timeout = setTimeout( function () { xhr.abort(); // call error callback}, 60*1000 /* timeout after a minute */ );xhr.open('GET', url, true); xhr.send();

In addition, you should avoid synchronous Ajax requests.

. Processing WebSocket timeout

Generally, after a WebSocket connection is created, if you are not active, the server will disconnect you 30 seconds later. The firewall also disconnects after a period of inactivity.

To prevent timeout, you may need to send an empty message intermittently to the server. To do this, you can add the following two functions in your code: one to maintain the connection and the other to cancel the connection. With this technique, you can control timeout issues.

Use a timerID:

var timerID = 0;function keepAlive() { var timeout = 15000; if (webSocket.readyState == webSocket.OPEN) { webSocket.send(''); } timerId = setTimeout(keepAlive, timeout);}function cancelKeepAlive() { if (timerId) { cancelTimeout(timerId); }}

The keepAlive () method should be added at the end of the onOpen () method connected to webSOcket, while cancelKeepAlive () should be added at the end of the onClose () method.

Forty-six. Keep in mind that the original operators are always more efficient than function calls. Use VanillaJS.

For example, do not use:

var min = Math.min(a,b);A.push(v);

Usage:

var min = a < b ? a b;A[A.length] = v;

Usage and functions of js operator single vertical bar "|" and js Data Processing

During the js Integer Operation, the decimal point is removed, parseInt. Math. floor () is equivalent to a positive number, and Math. ceil () is equivalent to a negative number. Note:

1. Math. ceil () is used as the rounded up integer. 2. Math. floor () is used for downgrading. 3. Math. round () the rounding round we often use in mathematics. Console. log (0.6 | 0) // 0console. log (1.1 | 0) // 1console. log (3.65555 | 0) // 3console. log (5.99999 | 0) // 5console. log (-7.777 | 0) //-7

Note: apart from the three Math methods for processing numbers, we often use parseInt (), parseFloat (), toFixed (), and toPrecision. Simple explanation:

The toFixed method is used as follows:

100.456001.toFixed(2); //100.47100.456001.toFixed(3); //100.456Number.prototype.toFixed.call(100.456001,2); //100.47

Disadvantage: it will become a string after use.

ToPrecision usage:

99.456001.toPrecision(5); //99.456100.456001.toPrecision(5); //100.46Number.prototype.toPrecision.call(10.456001,5); //10.456

Operation Rules for single vertical bars

After reading the example above, we generally know that the single vertical bar can be used to perform an integer operation, that is, only the positive part is retained, and the fractional part is removed, but "| 0 ", how is the computation performed? Why can "| 0" be used to achieve the goal of an integer? What if a single vertical bar is not 0?

With these questions, let's look at the following example:

console.log(3|4); //7console.log(4|4);//4console.log(8|3);//11console.log(5.3|4.1);//5console.log(9|3455);//3455

It seems that there is no rule to look? Search online. Http://tools.jb51.net/table/priority

Here we mention the single vertical bar "|" but there is no javascript.

Okay, let me publish the answer here. In fact, a single vertical bar "|" is the result obtained after being converted to a binary hexadecimal notation. For example, let's take a simple example:

3 | after 4 is converted to binary, 011 | 100 is obtained after 111 = 74 | 4 is converted to binary. 100 | 100 is obtained after 100 is added to the binary. 48 | 3 is obtained after 1000 is converted to binary. | is obtained after is added. 1011 = 11

And so on, I will not list them here. The single vertical bar "|" operation is the result obtained after being converted to a binary system! Have you learned everything?

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.