A comprehensive introduction to JavaScript practical skills and single vertical bar _javascript skills

Source: Internet
Author: User
Tags anonymous array length serialization setinterval wrapper

JavaScript itself can be regarded as a simple language, but we also continue to use the wisdom and flexibility of the model to improve it. Yesterday we applied these patterns to the JAVASCRIPT framework, and today these frameworks drive our WEB applications. Many novice developers are attracted to a variety of powerful JavaScript frameworks, but they ignore the JavaScript-like techniques behind the framework. This article will give you a comprehensive description of the points of knowledge.

The operation of a JS integer

Using | and ~ ~ can turn floating point into an integral type and be more efficient than similar parseint,math.round, which is useful when dealing with effects such as pixel and animation displacement. Performance comparison See this.

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

There is also a little trick, is!! 2 exclamation mark, you can speak a value and quickly convert to a Boolean value. You can test it!

var eee= "Eee";
Alert (!! Eee

Returns true, which means that any one value is preceded by!! All can be constant equals true. Unless this value is a Boolean value, or undefined, null, 0, False, Nan, ' because I mentioned undefined, null, 0, False, NaN, ', these are false, so add two!! After that, it's still fasle.

Second, rewrite the original alert, record the number of bomb frames

(function () {
 var oldalert = Window.alert,
 count = 0;
 Window.alert = function (a) {
 count++;
 Oldalert (A + "\ n ' ve called alert" + Count + "times now.") Stop, it ' s evil! ');
 }
();
Alert ("Hello haorooms");

Third, the digital exchange does not declare the intermediate variable method

Exchange between two numbers, our general practice is to declare an intermediate variable, but today's practice is more exotic, do not declare the middle variable, see how it is achieved!

var a=1,b=2;a=[b,b=a][0];
Console.log (' A: ' +a+ ', B: ' +b ');

 Output a:2,b:1

How is this approach a new feeling?

Four, all things are objects

In the JavaScript world, everything is the object. In addition to null and undefined, other basic type numbers, strings, and Boolean values have a wrapper object on them. A feature of an object is that you can call the method directly on it.

For a numeric base type, attempting to invoke the ToString method on it will fail, but the call will not fail when enclosed in parentheses, and the internal implementation is to convert the base type to an object with the appropriate wrapper object. So (1). ToString () is the equivalent of new number (1). ToString (). Therefore, you can really use the basic type numbers, strings, Boolean, etc. as objects, just pay attention to the syntax to be appropriate.

At the same time, we notice that the numbers in JavaScript are not floating-point and plastic, all numbers are floating-point types, just omit the decimal point, for example, you see 1 can be written as 1. And that's why when you try to 1.toString (), you get an error. So the correct way of writing should be this: 1. ToString (), or, as described above, with parentheses, where the parentheses function is to correct the JS parser, and do not take the point at the back of the 1 as a decimal. The internal implementation, as described above, is to 1. Use the wrapper object to convert to an object and then call the method.

The distortion of the IF statement

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

var day= (new Date). Getday () ===0;
The traditional if statement
if (day) {
 alert (' The ' is sunday! ');
};
Use logic and replace if
Day&&alert (' is sunday! ');

For example, the above code, first get today's date, if it is Sunday, the window, or do nothing. We know that there is a short-circuit in the logic operation, for logic and expressions, only the results are true, and if the preceding day variable is false, the result is false for the whole and the expression, so it will not continue to execute the following alert, if the preceding day is true, You will also continue to execute the following code to determine whether the entire expression is true or false. Use this to achieve the effect of IF.

For a traditional if statement, if the execution body code exceeds 1 statements, you need curly braces, and with a comma expression, you can execute arbitrary code without curly braces.

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

Six, use = = =, not = =

the = = (or!=) operator automatically performs type conversions when needed. the = = = = (or!==) operation does not perform any conversions. It compares values and types, and is also considered to be superior to = = in speed.

[ten] = = =/is False [ten] = =/is true ' = =/is ' true ' = = =/is False
 [] = = 0//IS True
 [] = = 0/is false
 ' = = false/is true but true = = "A" is false
 ' = = = False//is False

Vii. implementing private variables using closures

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;};

 Properties that are not initialized in constructors
 var occupation;
 This.getoccupation = function () {return occupation;};
 This.setoccupation = function (NEWOCC) {occupation = 
  newocc;};
}

Viii. creating a constructor for an object

function person (firstName, lastName) {
 this.firstname = firstName;
 This.lastname = LastName;
}

var Saad = new Person ("Saad", "Mousliki");


Nine, careful use of typeof, Instanceof and constructor

var arr = ["A", "B", "C"];
typeof Arr; Return "Object"
arr instanceof Array//True
arr.constructor ();//[]

X. Create a self-invocation function (self-calling funtion)

This is often referred to as a call to an anonymous function (self-invoked Anonymous function) or an instant call to a function expression (iife-immediately invoked function Expression). This is a function that is automatically executed immediately after it is created, usually as follows:

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

To get a random item from an array

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2145, 119];

var Randomitem = Items[math.floor (Math.random () * items.length)];

12. Get a random number within a certain range

This code fragment 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 maximum set value

var numbersarray = [], max = m;

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 (2));
 Return rdmstring.substr (0, Len);
}

Call Method Generaterandomalphanum (15);

Disrupt an array of numbers

var numbers = [5, 458, -215, 228, 122205, -85411];
Numbers = Numbers.sort (function () {return math.random ()-0.5});
/* The array numbers'll is equal for example to [120, 5, 228,-215, 400, 458,-85411, 122205] * * *

16, the TRIM function of string

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

17. Attach (append) an array to another array

var array1 = [, "foo", {name: "Joe"}, -2458];

var array2 = ["Doe", 555];
Array.prototype.push.apply (Array1, array2);
/* Array1 'll is equal to [, "foo", {name "Joe"}, -2458, "Doe", 555, 100] * *

18. Convert the arguments object into an array

var Argarray = Array.prototype.slice.call (arguments);
"Translator Note: The arguments object is a class array object, but not a true array"

19, verify that the parameter is a number

function Isnumber (n) {return
 !isnan (parsefloat (n)) && isfinite (n);
}

20. Verify that the parameter is an array

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

Note: If the ToString () method is rewritten (overridden), you will not get the desired result using this technique. Or you can use:

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

If you are not using multiple frames, you can also use the Instanceof method. But 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 won't work correctly, MyArray loses his constructor
//constructor are not shared BETW Een frames
arr instanceof Array;//False

"Translator Note: There is a lot of discussion about how to judge an array online, so you can Google it." This article is very detailed. 】

21. Gets the maximum or minimum value in a numeric array

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
var maxinnumbers = Math.max.apply (Math, numbers);
var mininnumbers = Math.min.apply (Math, numbers);
"Translator Note: Here is the technique of passing parameters using the Function.prototype.apply method."

22. Empty an array

var myarray = [A, 222, 1000];
myarray.length = 0; MyArray is equal to [].

23, do not use Delete to delete the items in an array.

Use splice instead of Delete to remove an item from an array. Using delete simply replaces the original item with the undefined and is not really removed from the array.

Do not use this method:

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119];
Items.length; Return one
items[3];//return True items.length//return/
* items would be
equal to [, 548, "a ", Undefinedx1, 5478," foo ", 8852, Undefinedx1," Doe ", 2154, 119] * *

and use:

var items = [548, ' a ', 2, 5478, ' foo ', 8852, ' Doe ', 2154, 119];
Items.length; Return one
items.splice (3,1);
Items.length; Return/
* items are equal to [548, "a", 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] * *

The Delete method should be used to delete a property of an object.

24. Use length to truncate an array

Like the way it empties the array above, we use the Length property to truncate an array.

var myarray = [A, 222, 1000, 124, N, ten];
Myarray.length = 4; MyArray would be equal to [12, 222, 1000, 124].

In addition, if you set the length of an array to a value larger than the current one, the lengths of the array will be changed, adding a new undefined item to fill. The length of the array is not a read-only property.

Myarray.length = 10; The new array length is
myarray[myarray.length-1];//undefined

25. Use logical and/or to make conditional judgments

Same as (v), if variant statement!

var foo = ten;
Foo = = && dosomething (); Equivalent to if (foo = =) dosomething ();
Foo = = 5 | | DoSomething (); Equivalent to if (foo!= 5) dosomething ();


Logical and can also be used to set default values for function arguments

function DoSomething (arg1) {
 Arg1 = arg1 | | 10;//If Arg1 is not set, ARG1 will be set by default

26, using the map () method to traverse an array of items

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

27, rounding a number, keep n decimal

var num =2.443242342;
num = num.tofixed (4); Num'll is equal to 2.4432

28. Floating point numbers

0.1 + 0.2 = = 0.3/is false
9007199254740992 + 1/are equal to 9007199254740992
9007199254740992 + 2/are EQ UAL to 9007199254740994

Why is that? 0.1+0.2 equals 0.30000000000000004. You know, all of the JavaScript numbers are internally floating points in 64-bit binary notation, in line with the IEEE 754 standard. For more information, you can read this blog post. You can use the toFixed () and Toprecision () methods to solve this problem.

29, the use of for-in to traverse an object's internal properties of the time to pay attention to check properties

The following code fragment avoids accessing the properties of a prototype while traversing an object property

for (var name in object) {
 if (Object.hasownproperty (name)) {
 //does something with name
 }
}

30. Comma operator

var a = 0;
var B = (a++,);
Console.log (a); A would be equal to 1
console.log (b);//b. Equal to 99

31. Caching variables that need to be computed and queried (calculation or querying)

For the jquery selector, 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 ');

32. Validate parameters before calling Isfinite ()

Isfinite (0/0); False
isfinite ("foo");//False
Isfinite ("ten");//True
isfinite (a);//True
isfinite (undifined); False
isfinite ();//False
isfinite (null);//True!!!

33, avoid the negative index in the array (negative indexes)

var numbersarray = [1,2,3,4,5];
var from = Numbersarray.indexof ("foo"); From is equal to-1
numbersarray.splice (from,2);//would return [5]

Make sure that the argument when calling IndexOf is not a negative number.

34. Serialization and deserialization based on JSON (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 ":" department ": {" ID ":" "Name": "R&d"} "* *
var personfromstring = Json.parse (Stringfromperson);
/* personfromstring is equal to person object * *

35. Avoid using the eval () and function constructors

Using the Eval and function constructors is a very expensive operation because each time they invoke the script engine to convert the source code into executable code.

var func1 = new Function (functioncode);
var Func2 = eval (functioncode);

36. Avoid using with ()

using with () inserts a global variable. Therefore, a variable with the same name can be overridden to cause unnecessary trouble.

37, avoid using for-in to traverse an array

Avoid the use of 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 added benefit is that the values of the I and Len two variables are executed only once, and are more efficient than the following:

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

Why? Because the arraynumbers.length is counted every time it loops.

38. When calling SetTimeout () and SetInterval (), pass in the function instead of the string.

If you pass a string to settimeout () or setinterval (), the string will be parsed as if using eval, which is time-consuming.

Do not use:

SetInterval (' dosomethingperiodically () ', 1000);
SetTimeout (' Dosomethingafterfiveseconds () ', 5000)

and use:

SetInterval (dosomethingperiodically, 1000);
SetTimeout (Dosomethingafterfiveseconds, 5000);

39, the use of switch/case statements, not a long series of if/else

Using Switch/case is more efficient and elegant (easier to organize code) when you're judged to be more than 2. But do not use switch/case when judging more than 10 kinds of cases.

40. Use Switch/case when judging the range of values

In the following case, it is reasonable to use switch/case to judge the range of values:

function GetCategory (age) {
 var category = "";
 Switch (true) {case
 isNaN (age):
 category = ' not ' age ';
 break;
 Case (age >=):
 category = "old";
 break;
 Case (age <=):
 category = "Baby";
 break;
 Default:
 category = "Young";
 break;
 };
 return category;
}
GetCategory (5); would return "Baby"

"Translator Note: generally for the judgement of the range of values, with If/else will be more appropriate." Switch/case is more suitable for determining the value of a decision "

41. Specify the prototype object for the created object

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

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

42, an HTML escape function

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

43. Avoid using try-catch-finally inside the loop

At run time, each time a catch clause is executed, the captured exception object is assigned to a variable, and in the try-catch-finally structure, the variable is created each time.

Avoid such a writing:

var object = [' foo ', ' Bar '], I;
for (i = 0, len = object.length i <len; i++) {The
 try {
 //do something this throws an exception
 }
 CA TCH (e) {
 //Handle exception
 }
}

and use:

var object = [' foo ', ' Bar '], I;
try {
 for (i = 0, len = object.length i <len; i++) {
 //does something that throws a exception
 }
}
catch (E) {
 //handle Exception
}

44, for the xmlhttprequests set timeout.

When a XHR request takes a long time (for example, due to a network problem), you may need to abort the request, so you can use settimeout () for the XHR call.

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 ER ROR callback
}, 60*1000/* Timeout after a minute * *);
Xhr.open (' Get ', url, true); 

Xhr.send ();

Also, generally you should avoid synchronous AJAX requests altogether.

45, processing WebSocket timeout

Typically, after a websocket connection is created, if you do not have an activity, the server will disconnect your connection after 30 seconds. The firewall also disconnects after a period of inactivity.

To prevent timeouts, you may need to send empty messages to the server intermittently. To do this, you can add the following two functions to your code: one to keep the connection, and the other to cancel the connection's retention. With this technique, you can control the timeout problem.

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 of the WebSocket connection, while cancelkeepalive () is added at the end of the OnClose () method.

46. 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);

and use:

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

47, from the integer, randomly select a value

The following formula, very useful, allows us to randomly display some famous quotes or news events!

Value =math.floor (Math.random () * Total number of possible values + first possible value)
For example: To select a value between 2 and 10, we can write this

var Num=math.floor (Math.random () *9+2)

Please remember the formula above! ~

JS operator single vertical bar "|" The usage and function of JS and data processing

Just in the JS integer operation, the equivalent of removing the decimal point, parseint. When a positive number is equivalent to Math.floor (), a negative number is equivalent to the Math.ceil () Note:

1. Math.ceil () is used for rounding up.
2. Math.floor () is used for rounding down.
3. Math.Round () The rounded rounding we used in mathematics.

Console.log (0.6|0)//0
console.log (1.1|0)//1 console.log
(3.65555|0)//3 console.log
(5.99999|0)/ /5
Console.log ( -7.777|0)//-7

Note: We often use parseint (), parsefloat (), toFixed () and toprecision () and so on, in addition to the math's three methods for handling numbers. Simple explanation:

The Tofixed method uses the following:

100.456001.toFixed (2); 100.47

100.456001.toFixed (3);//100.456

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

Disadvantage: After use, it will become a string.

Toprecision usage is as follows:

99.456001.toPrecision (5); 99.456

100.456001.toPrecision (5);//100.46

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

Rule of operation of single vertical bar

Look at the above example, the general know that a single vertical bar can be used to take the whole operation, that is, only the positive part, the decimal part by taking off, but "|", and how to operate it, why can "|" to achieve the purpose of rounding? The single vertical bar is not 0 What is the number?

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

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

Like there's no law to look for? Search online. Http://tools.jb51.net/table/priority

This refers to the single vertical bar "|" But there's no JavaScript.

All right, I'm here to announce the answer. In fact, single vertical bar "|" Is the result of the addition of the conversion to the 2 binary. For example, let's take a simple example:

3|4 after
conversion to binary 011|100 add to 111=7

4|4 converted to
binary 100 |100 add get 100=4 8|3
convert to binary 1000 |011 Add to get 1011=11

And so on, I'm not going to enumerate here, single vertical bar "|" The operation is to convert to 2 after the addition of the result! Have you learned?

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.