Practical native API aggregation in JavaScript _ javascript skills

Source: Internet
Author: User
During this time, I doubled the JavaScript api and found a lot of good wheels, saving me trouble. The following is a summary. For more information, see. Go to the topic

Parses string objects

We all know that JavaScript objects can be serialized as JSON or parsed as objects, but the problem is that if there is a "thing" that is neither JSON nor object ", it is inconvenient to turn to any party, so eval can be used.

Var obj = "{a: 1, B: 2}"; // looks like the object's string eval ("(" + obj + ")") // {: 1, B: 2}

Because eval can execute a string expression, we want to execute the obj String object into a real object, then we need to use eval. However, to avoid eval executing the obj statement with {}, we set () outside the obj so that it can be parsed into an expression.

& (Bitwise AND)

To determine whether a number is a power of 2, you can subtract a power from itself.

var number = 4(number & number -1) === 0 // true

^ (By bit or)

If the third variable is different, the values of the two variables can be exchanged.

var a = 4,b = 3a = a ^ b //  7b = a ^ b //  4a = b ^ a //  3

Format Date

Do you want to get the time after format? Now you don't need to get year, month, day, hour, minute, second, three steps.

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? Use the Date constructor directly

new Date("2015-5-7 9:04:10");// Thu May 07 2015 09:04:10 GMT+0800 (CST)

Want to convert a standard time object to a unix timestamp? ValueOf.

(new Date).valueOf();// 1431004132641

Many friends also reminded me to get the timestamp quickly.

+ New Date

Mona1 Addition

One-dollar addition can quickly convert string numbers into mathematical numbers, that is

var number = "23" typeof number // stringtypeof +number // number

You can convert a time object to a timestamp.

new Date // Tue May 12 2015 22:21:33 GMT+0800 (CST)+new Date // 1431440459887

Escape URI

You need to pass the url as a parameter in the route. Now escape it

var url = encodeURIComponent('http://segmentfault.com/questions/newest')// "http%3A%2F%2Fsegmentfault.com%2Fquestions%2Fnewest"

Escape again

decodeURIComponent(url)// "http://segmentfault.com/questions/newest"

Number

The number of decimal places to be retained. toFixed removes the number of decimal places.

number.toFixed()   // "12346"number.toFixed(3)  // "12345.679"number.toFixed(6)  // "12345.678900"

The parameter range is 0 ~ 20. If this parameter is left blank, the default value is 0.

Type Detection

Typeof is the most frequently used type detection method.

typeof 3    // "number"typeof "333"  // "string"typeof false  // "boolean"

The basic (simple) data type is quite good, but once the data type is referenced

typeof new Date()  // "object"typeof []      // "object"typeof {}      // "object"typeof null     // "object"   

The first three are tolerable. null returns an object. Are you kidding me !!! (Ps: in fact, this is a JavaScript bug. I don't want to remove it)

At this time, we will use instanceof

toString instanceof Function// true(new Date) instanceof Date// true[] instanceof Object// true[] instanceof Array// true

In fact, we can find that [] and Object get true. Although we know that [] is also an Object, we hope to have a more accurate method for determining the type. Now it comes
Object. prototype. toString () is used for determination. To make every Object pass the detection, we need to call it in the form of Function. prototype. call or Function. prototype. apply.

var toString = Object.prototype.toString;toString.call(new Date)  // "[object Date]"toString.call(new Array)  // "[object Array]"toString.call(new Object) // "[object Object]"toString.call(new Number) // "[object Number]"toString.call(new String) // "[object String]"toString.call(new Boolean) // "[object Boolean]"

Note that the toString method is very likely to be overwritten, so when you need to use it,
You can directly use the Object. prototype. toString () method.

Implement inheritance

Let's look at an official example.

//Shape - superclassfunction Shape() { this.x = 0; this.y = 0;}Shape.prototype.move = function(x, y) {  this.x += x;  this.y += y;  console.info("Shape moved.");};// Rectangle - subclassfunction 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."

Get the initialization attributes and methods through call, and get the attributes and methods on the prototype Object through Object. create.

Iteration

ES5 has many iterative functions, such as map, filter, some, every, and reduce.

Array

The specific api is described in detail here.
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Glob...
Here is a few words:
Join, pop, push, reverse, shift, sort, splice, unshift will change the original array

Concat, indexOf, lastIndexOf, slice, toString will not change the original array

The Iterative Methods map, filter, some, every, reduce, and forEach do not change the original array.

Notes:

1 shift, pop will return the deleted Element
2 splice returns an array composed of deleted elements or an empty array.
3. push returns the length of the new array.
4. some is stopped when the value is true.
5 every stops when there is false
6. The above iteration method can append the thisArg parameter at the end, which is the this value when callback is executed.

The above is all the content of this article. I hope you will like it.

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.