JavaScript's pretty code snippets _javascript tips

Source: Internet
Author: User
Tags numeric value

Dynamic construction of regular expressions

Copy Code code as follows:

New RegExp (expr.match[type].source + (/?!) [^\[]*\]) (?! [^\(]*\)) /.source))

From sizzle, when dynamically building regular, this avoids character escaping.


More flexible and ingenious Digital 0

Copy Code code as follows:

function Prefixinteger (num, length) {
Return (Num/math.pow (length)). toFixed (length). substr (2);
}

Take the maximum and minimum values of an array

Copy Code code as follows:

Math.max.apply (Math, [1,2,3])//3
Math.min.apply (Math, [1,2,3])//1

To produce pretty random strings

Copy Code code as follows:

Math.random (). toString. substring (2); 8-bit
Math.random (). toString. substring (2); 16-bit


Get time stamp

Relative to
var timeStamp = (new Date). GetTime ();
The following ways are more convenient:

Copy Code code as follows:

var timeStamp = number (new Date);

Convert to numeric value and rounding

Copy Code code as follows:

var result = ' 3.1415926 ' | 0; 3


String formatting

Copy Code code as follows:

function format (format) {
if (! Fb. String.format._formatre) {
Fb. String.format._formatre =/(\{[^\}^\{]+\})/g;
}

var values = arguments;

Return Format.replace (
Fb. String.format._formatre,
function (str, m) {
Var
index = parseint (M.SUBSTR (1), 10),
Value = Values[index + 1];
if (value = = NULL | | value = = undefined) {
Return ";
}
return value.tostring ();
}
);
}


Use:
Copy Code code as follows:

Format (' {0}.facebook.com/{1} ', ' www ', ' login.php ');
-> www.facebook.com/login.php

Swap the value of a two variable

Copy Code code as follows:

var foo = 1;
var bar = 2;
foo = [bar, bar=foo][0];

REGEXP Looping

Copy Code code as follows:

String.prototype.format = function (///* args * *) {
var args = arguments;
Return This.replace (
/\{(\d+) \}/g,
function (full, IDX) {
return ARGS[IDX];
} )
}

' Hello {0}, how{1} '. Format (' Bob ', ' you Doin ');
=> Hello Bob, how do you doinhttp://mazesoul.github.com/readability_idioms_and_compression_tolerance/#31.0

Definition is run function

Copy Code code as follows:

(function () {
Do something
} )();

This is really the simplest technique, but it is also the most practical technique. Lays the foundation for JavaScript encapsulation.

Ternary operation

Copy Code code as follows:

var some = Con1? Val1:
Con2? Val2:
Con3? VAL3:
Defaultval;

A function registration-invocation mechanism

From CKEditor, I made the extraction.

Copy Code code as follows:

(function () {
var FNS = [];
Converts an object with the available subscript access attribute to an array
Note that IE Domnodelist will fail
function ToArray (arraylike, index) {
Return Array.prototype.slice.call (arraylike, index | | 0);
}
Window. Util = {
' AddFunction ': function (FN, scope) {
Return Fns.push (function () {
return fn.apply (Scope | | window, arguments);
})-1;
},

' Removefunction ': function (index) {
fns[index] = null;
},

' CallFunction ': function (index) {
var fn = fns[index];

RETURN FN && fn.apply (window, ToArray (arguments, 1));
}
};
} )();
Application Scenarios
var Fnid;
In the closure, add a function that can be called globally
(function () {
Fnid = util.addfunction (function (msg) {
Alert (msg);
} );
} )();

Call
Util.callfunction (Fnid, ' Hello, World '); -> ' Hello,world ';

Short circuit operation

Copy Code code as follows:

var something = ' xxxx ';
Console.log (True && something); -> ' xxx ';
Console.log (false && something); -> false
Console.log (true | | | something); -> true
Console.log (False | | something); -> something

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.