A practical native API rollup in JavaScript

Source: Internet
Author: User
Tags array length bitwise constructor eval json tostring

This time over a JavaScript API, found a lot of good wheels, save the trouble of making. Here is a summary of the following, the need for small partners can refer to.

Go straight to the point

Parsing String objects

As we all know, JavaScript objects can be serialized as Json,json or parsed into objects, but the problem is that if there is a "thing" that is neither JSON nor an object, it's inconvenient to turn to either side, and Eval can come in handy.

?

1 2 var obj = "{a:1,b:2}"; Looks like an object's string eval ("+ obj +"))//{a:1, b:2}

Because Eval can execute a string expression, we want to execute the object of obj as a real object, then we need to use Eval. But to avoid eval executing with the {} obj as a statement, we set the pair () outside of obj to be parsed into an expression.

& (Bitwise AND)

To determine whether a number is 2 n power, you can reduce it with its own phase

?

1 2 var number = 4 (number & number-1) = = 0/True

^ (Bitwise XOR OR)

Unlike the third variable, you can swap the value of two variables

?

1 2 3 4 var a = 4,b = 3 A = a ^ b//7 B = a ^ b//4 A = b ^ A//3

Format Date

What time does it take to get the format? Now you don't have to get the day and the month, three steps.

?

1 2 3 4 5 var temp = new Date (); var regex =///g;   (temp.tolocaledatestring () + ' + temp.tolocaletimestring (). Slice (2)). Replace (regex, '-'); "2015-5-7 9:04:10"

Want to convert the time after format to a time object? directly using the date constructor

?

1 2 3 New Date ("2015-5-7 9:04:10"); Thu May 2015 09:04:10 gmt+0800 (CST)

Want to convert a standard time object to a Unix timestamp? valueof.

?

1 2 3 (new Date). valueof (); 1431004132641

Many friends also remind you that you can quickly get a timestamp.

+new Date

One dollar Plus

Unary Plus can quickly convert a string number to a mathematical number, which is

?

1 2 3 var number = "typeof" number//String typeof +number//number

You can convert a time object to a timestamp

?

1 2 New Date//Tue May 2015 22:21:33 gmt+0800 (CST) +new Date//1431440459887

Escape URI

You need to pass the URL as a parameter in the route and now escape the

?

1 2 3 var url = encodeuricomponent (' http://segmentfault.com/questions/newest ')//"http%3a%2f%2fsegmentfault.com% 2fquestions%2fnewest "

and then reverse righteousness.

?

1 2 decodeURIComponent (URL)//"Http://segmentfault.com/questions/newest"

Number

Want to keep a few decimal places after the decimal point, do not have to do string interception, tofixed take away

?

1 2 3 Number.tofixed ()//"12346" number.tofixed (3)//"12345.679" number.tofixed (6)//"12345.678900"

Parameter range is 0~20, do not write default 0

Type detection

typeof is the most frequently used type detection method.

?

1 2 3 typeof 3//"number" typeof "333"//"string" typeof false//"Boolean"

It's good for basic (simple) data types, but when it comes to referencing data types, it's not going to be easy.

?

1 2 3 4 typeof new Date ()//"Object" typeof []//"Object" typeof {}//"object" typeof Null//"Object"

The first three can endure, null incredibly also return object, you are teasing me!!! (PS: This is actually a JavaScript bug people difficult not to dismantle ꒰・◡・๑꒱)

At this time, we will use instanceof

?

1 2 3 4 5 6 7 8 toString instanceof Function//True (new Date) instanceof Date//True [] instanceof Object//True [] instanceof Array/ /True

In fact, we can see that [] and object get true, although we know that [] is an object, but we want a way to judge the type more accurately, and now it's coming

Using Object.prototype.toString () to determine, in order for each object to pass detection, we need to use the form of Function.prototype.call or Function.prototype.apply to invoke

?

1 2 3 4 5 6 7 8 var toString = Object.prototype.toString; Tostring.call (new date)//"[Object Date]" Tostring.call (new Array)//[Object Array] Tostring.call (New object)//[obj ECT Object] "Tostring.call (new number)//[object number]" Tostring.call (new String)//"[Object String]" Tostring.call (n EW Boolean)//"[Object Boolean]"

Note that the ToString method is very likely to be rewritten, so when you need to use it,

You can use the Object.prototype.toString () method directly

Implementing inheritance

Look at an official example.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24-25 Shape-superclass function Shape () {this.x = 0; this.y = 0;}   Shape.prototype.move = function (x, y) {this.x = = x; this.y + = y; Console.info ("Shape moved.");   Rectangle-subclass function Rectangle () {shape.call (this);//call Super constructor.}   Rectangle.prototype = Object.create (Shape.prototype);   var rect = new Rectangle (); Rect instanceof Rectangle//true.   Rect instanceof Shape//true. Rect.move (1, 1); Outputs, "Shape moved."

Call to get the initialized properties and methods, through Object.create to get the properties and methods on the prototype object

Iterations

ES5 out a lot of iterative functions, such as Map,filter,some,every,reduce

Array

The specific API is described here in detail.

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Glob ...

Here are a few words:

Join,pop,push,reverse,shift,sort,splice,unshift will change the original array.

Concat,indexof,lastindexof,slice,tostring does not change the original array

Map,filter,some,every,reduce,foreach These iterative methods do not change the original array

Several points to note:

1 Shift,pop will return the deleted element.

2 Splice will return an array of deleted elements, or an empty array

3 Push will return the new array length

4 some to stop when there is true

5 Every to stop when there's false.

6 The above iteration method can append a parameter thisarg at the end, which is the this value when executing the callback.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.