Summary of common JS functions and techniques, and summary of js skills

Source: Internet
Author: User
Tags git commands

Summary of common JS functions and techniques, and summary of js skills

What is summarized during the learning and work process, including common functions, common js skills, common regular expressions, git notes, and so on. It provides a simple query method for children shoes who are new to the front-end, and remembers the path of front-end learning.

Ajax request

Jquery ajax Functions

I encapsulated an ajax function by myself. The Code is as follows:

Var Ajax = function (url, type success, error) {$. ajax ({url: url, type: type, dataType: 'json', timeout: 10000, success: function (d) {var data = d. data; success & success (data) ;}, error: function (e) {error & error (e) ;}}; // usage: ajax ('/data. json', 'get', function (data) {console. log (data );});

Jsonp Method

Sometimes we use the jsonp Method for cross-origin purposes. I also encapsulate a function:

Function jsonp (config) {var options = config | |{}; // the url, success, time, and fail attributes var callbackName = ('jsonp _ '+ Math. random ()). replace (". "," "); var oHead = document. getElementsByTagName ('head') [0]; var oScript = document. createElement ('script'); oHead. appendChild (oScript); window [callbackName] = function (json) {// create the jsonp callback function oHead. removeChild (oScript); clearTimeout (oScript. timer); window [callbackN Ame] = null; options. success & options. success (json); // Delete the script tag first. The success function is actually executed.}; oScript. src = options. url + '? '+ CallbackName; // send the request if (options. time) {// set timeout to process oScript. timer = setTimeout (function () {window [callbackName] = null; oHead. removeChild (oScript); options. fail & options. fail ({message: "timeout"}) ;}, options. time) ;}}; // usage: jsonp ({url: '/B .com/ B .json', success: function (d) {// data processing}, time: 5000, fail: function () {// error handling }});

Regular Expression

Mobile phone number verification

var validate = function(num) {var exp = /^1[3-9]\d{9}$/;return exp.test(num);};

ID card number verification

var exp = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;

Ip address verification

var exp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

Common js Functions

$(window).scroll(function() {var a = $(window).scrollTop();if(a > 100) {$('.go-top').fadeIn();}else {$('.go-top').fadeOut();}});$(".go-top").click(function(){$("html,body").animate({scrollTop:"0px"},'600');});

Prevents bubbles

Function stopBubble (e) {e = e | window. event; if (e. stopPropagation) {e. stopPropagation (); // W3C blocking Bubble Method} else {e. cancelBubble = true; // IE blocking the Bubble Method }}

ReplaceAll

Var replaceAll = function (bigStr, str1, str2) {// replace all str1 in bigStr with str2var reg = new RegExp (str1, 'G'); return bigStr. replace (reg, str2 );}

Obtain the parameter values in the browser url

var getURLParam = function(name) {return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;};

Deep copy object

function cloneObj(obj) {var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());for(var key in obj){if(o[key] != obj[key] ){if(typeof(obj[key]) == 'object' ){o[key] = mods.cloneObj(obj[key]);}else{o[key] = obj[key];}}}return o;}

Array deduplication

Var unique = function (arr) {var result = [], json = {}; for (var I = 0, len = arr. length; I <len; I ++) {if (! Json [arr [I]) {json [arr [I] = 1; result. push (arr [I]); // return elements not deleted} return result ;};

Checks whether array elements are repeated.

Var isRepeat = function (arr) {// does arr have duplicate element var hash ={}; for (var I in arr) {if (hash [arr [I]) return true; hash [arr [I] = true;} return false ;};

Generate random number

function randombetween(min, max){return min + (Math.random() * (max-min +1));}

Operation cookie

own.setCookie = function(cname, cvalue, exdays){var d = new Date();d.setTime(d.getTime() + (exdays*24*60*60*1000));var expires = 'expires='+d.toUTCString();document.cookie = cname + '=' + cvalue + '; ' + expires;};own.getCookie = function(cname) {var name = cname + '=';var ca = document.cookie.split(';');for(var i=0; i< ca.length; i++) {var c = ca[i];while (c.charAt(0) == ' ') c = c.substring(1);if (c.indexOf(name) != -1) return c.substring(name.length, c.length);}return '';};

Knowledge and skills

Data Type

Underfined, null, 0, false, NaN, empty string. Their logical non-result values are true.

Closure format

Benefit: avoid name conflicts (global variable contamination ).

(function(a, b) {console.log(a+b); //30})(10, 20);

Truncate and clear Arrays

Var arr = [12,222, 44, 88]; arr. length = 2; // intercept, arr = [12,222]; arr. length = 0; // empty, arr will be equal to [].

Obtains the maximum and minimum values of an array.

var numbers = [5, 45822, 120, -215];var maxInNumbers = Math.max.apply(Math, numbers); //45822var minInNumbers = Math.min.apply(Math, numbers); //-215

Floating Point Calculation Problems

0.1 + 0.2 == 0.3 //false

Why? Because 0.1 + 0.2 equals 0.30000000000000004. All JavaScript numbers follow the IEEE 754 standard and are represented by 64-bit floating point decimals internally. You can solve this problem by using toFixed.

Array sorting sort function

Var arr = [1, 5, 6, 3]; // number array arr. sort (function (a, B) {return a-B; // return B-a from small to large; // return Math from large to small. random ()-0.5; // array shuffling}); var arr = [{// object array num: 1, text: 'num1'}, {num: 5, text: 'num2'}, {num: 6, text: 'num3'}, {num: 3, text: 'num4'}]; arr. sort (function (a, B) {return. num-B. num; // return B from small to large. num-. num; // from large to small });

Object and String Conversion

var obj = {a: 'aaa', b: 'bbb'};var objStr = JSON.stringify(obj); // "{"a":"aaa","b":"bbb"}"var newObj = JSON.parse(objStr); // {a: "aaa", b: "bbb"}

Git notes

Git uses the previous configuration

1. git config -- global user. email xxx@163.com

2. git config -- global user. name xxx

3. ssh-keygen-t rsa-C xxx@163.com (email address) // generate ssh

4. Find the. ssh folder and open it. Use cat id_rsa.pub // to open the Public Key ssh string.

5. log on to github and set-SSH keys-add ssh keys (add all the above content)

(And then the mailbox (xxxxx@gmail.com) corresponding account on github has the permission to operate on the warehouse. You can execute the following git commands.

Common git commands

1. git config user. name/user. email // view the current git user name and email address

2. git clone https://github.com/jarson7426/javascript.git project // clone repository to local.

3. Modify the local code and submit it to the branch: git add file/git commit-m "add file"

4. push the local database to the remote database: git push origin master

5. view the commit log: git log-5

6. Return a version: git reset -- hard 123

7. branch: git branch/git checkout name/git checkout-B dev

8. merge the name branch to the current branch: git merge name/git pull origin

9. Delete the local branch: git branch-D name

10. delete a remote branch: git push origin: daily/x. x. x

11. git checkout-B mydev origin/daily/1.0.0 // map the remote daily branch to the local mydev branch for development
12. Merge remote branches to the current branch git pull origin daily/1.1.1

13. Publish to production:

Git tag publish/0.1.5
Git push origin publish/0.1.5: publish/0.1.5

14. Overwrite online code locally:

Git checkout -- theirs build/scripts/ddos
Git checkout -- theirs src/app/ddos

The above is a summary of common JS functions and skills introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave a message. The editor will reply to you in time, thank you very much for your support for the help House website!

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.