Javascript is commonly used to summarize

  • 2020-03-30 04:28:40
  • OfStack

No esoteric interpretation of the js some underlying principle in this chapter, such as this pointer, scope, prototype, involved are beneficial to simplify the code when development at ordinary times, improve the efficiency of execution, or can be used as a method of experience, length is not long, all steps run let you read the whole article, experience the joy of programming.

  Gets a random number within two intervals


function getRandomNum(Min, Max){ //Gets a random number
within two intervals     //Backfire & NBSP; It is possible that the first parameter is greater than the second parameter, so it is more reliable to increase the judgment
    if (Min > Max)
    Max = [Min, Min = Max][0]; //Quickly swap two variable values
   
    var Range = Max - Min + 1;
    var Rand = Math.random();
    return Min + Math.floor(Rand * Range);
};

Returns a positive/negative argument at random


function getRandomXY(num){ //Returns a random positive/negative parameter
    num = new Number(num);
    if (Math.random() <= 0.5)
        num = -num;
    return num;
}

  SetInterval () or setTimeOut() timer function pass arguments


var s = ' I am a parameter ';
function fn(args) {
    console.log(args);
}
var a = setInterval(fn(s),100);    //XXXXX
var b = setInterval(function(){    //Correct, the function
is timed with an anonymous function call     fn(s);
}, 100);

Recursive call to setInterval() or setTimeOut() timer


var s = true;
function fn2(a, b){        //  Step 3
    if (s) {
        clearInterval(a);
        clearInterval(b);
    }
};
function fn(a){     //  Step 2
    var b = setInterval(function(){
        fn2(a, b) //Pass in two timers
    }, 200)
};
var a = setInterval(function(){      //  Step 1
    fn(a); //B represents the timer itself and can be passed as an argument
}, 100);

Converts a string to a number


//No new Number (String)     You don't need a Number(String) you just need a String minus zero to be
var str = '100';  // str: String
var num = str - 0;// num: Number

A null value judgment


var s = '';  //Empty string
if(!s)         //An empty string is converted to Boolean false by default and can be written directly in a judgment statement < br / > if(s != null) //But empty strings! = null < br / > if(s != undefined) //Empty strings too! = undefined < br / >

Internet explorer parseInt() method


//The following conversion is 0 in IE and 1 in other browsers, depending on how IE interprets Numbers
var iNum = parseInt(01);
//Therefore, the compatible notation is
var num = parseInt(new Number(01));

Firebug makes it easy to debug js code


//Firebug has a built-in console object that provides built-in methods for displaying information
/**
 * 1:console.log() Can be used instead alert() or document.write() , support placeholder output, characters ( %s ), integer ( %d or %i ), floating point number ( %f ) and object ( %o ). Such as: console.log("%d years %d month %d day ",2011,3,26)
 * 2 If there is too much information, it can be displayed in groups console.group() and console.groupEnd()
 * 3 : console.dir() You can display all the properties and methods of an object
 * 4 : console.dirxml() A node used to display a web page ( node ) html/xml code
 * 5 : console.assert() An assertion that determines whether an expression or variable is true
 * 6 : console.trace() To trace the call path of the function
 * 7 : console.time() and console.timeEnd() , to show the running time of the code
 * 8 : performance analysis ( Profiler ) is to analyze the running time of various parts of the program and find out where the bottlenecks are console.profile()....fn....console.profileEnd()
 */

  Quickly takes the number of milliseconds of the current time


//T == the valueOf the current system milliseconds, because the + operator will call the valueOf () method of Date. < br / > var t = +new Date(); 

Take decimal and integer places quickly


//X == 2, the following x values are 2, negative Numbers can also be converted
var x = 2.00023 | 0;
// x = '2.00023' | 0;

Swap the values of two variables )


var a = 1;
var b = 2;
a = [b, b=a][0]
alert(a+'_'+b)    //The result is 2_1, the values of a and b have been swapped. < br / >

  Logic or '||' operator


//B is not null:a=b, b is null:a=1. < br / > var a = b || 1;
//The more common usage is to pass arguments for a plug-in method, and to get the event target element: event = event || window.event
//IE has a window.event object, whereas FF does not. < br / >

Only method objects have prototype properties


//Method has the prototype property of the object, which the raw data does not have, such as & NBSP; Var a = 1, a has no prototype
function Person() {} //Human constructor
Person.prototype.run = function() { alert('run...'); } //Prototype run method
Person.run(); // error
var p1 = new Person(); //The prototype run method is assigned to p1
only when the new operator is used p1.run(); // run...

Quickly get the day of the week


//The current time of the calculation system is the day of the week
var week = " Today is: Monday " + " One, two, three, four, five, six ".charat(new date().getDay());

The closure of prejudice


/**
 * Closure: any one js The method body can be called a closure, not something that only happens when an embedded function references an argument or property of an external function.
 * It has a separate scope in which several subscopes (that is, method nesting methods) can exist, and the closure is ultimately the scope of the outermost method
 * It contains its own method parameters and the method parameters of all nested functions, so when an nested function has a reference outside of it, the scope of the reference is the (top-level) method scope of the referenced function
 */
function a(x) {
    function b(){
        alert(x); //References to the external function parameter
    }
    return b;
}
var run = a('run...');
//Because of the scope expansion, you can refer to the variables of the outer function a and display
run(); // alert(): run..

Gets the address parameter string and a timed refresh


//Get the question mark? The rest, including the question mark
var x = window.location.search
//Gets the contents after the warning #, including the #
var y = window.location.hash
//With the timer to achieve web page automatically refresh
window.location.reload();

Null, and Undefined


/**
 * Undefined The type has only one value, that is undefined . When the declared variable is not initialized, the default value of the variable is undefined .
 * Null The type also has only one value, that is null . null Used to represent an object that does not yet exist. Often used when a function attempts to return a nonexistent object.
 * ECMAScript think undefined from null Derived, so they're defined to be equal.
 * But what if, in some cases, we had to distinguish between these two values? You can use the following two methods
 * When making judgments, it is best to use ' ===' Strong type judgment.
 */
var a;
alert(a === null); //False, because a is not an empty object
alert(a === undefined); //True, because a is uninitialized, undefined
//Extended < br / > alert(null == undefined); //True, because the '==' operator casts,
//Similarly < br / > alert(1 == '1'); // true
alert(0 == false); //True,false converts to Number of type 0

  Dynamically add parameters to the method


//Method a has an extra parameter 2
function a(x){
    var arg = Array.prototype.push.call(arguments,2);
    alert(arguments[0]+'__'+arguments[1]);
}

Customize the SELECT border style


<!-- Copy to the page to try it out. Feel free to customize the style -->
<span style="border:1px solid red; position:absolute; overflow:hidden;" >
    <select style="margin:-2px;">
        <option> The custom SELECT Border style </option>
        <option>222</option>
        <option>333</option>
    </select>
</span>

The simplest palette


<!-- JS To extract the value Value can set any color to any object -->
<input type=color />

Function, object is array?


var anObject = {}; //An object
anObject.aProperty = " Property of object " ; //Object
anObject.aMethod = function(){alert( " Method of object " )}; //Object
//See mainly the following:
alert(anObject[ " aProperty " ]); //The
property can be accessed as an array with the property name as the index anObject[ " aMethod " ](); //The method
can be called with the square name of the object as the index of the array for( var s in anObject) //Iterating through all the properties and methods of the object
alert(s + " is a " + typeof(anObject[s]));
//The same is true for objects of type function:
var aFunction = function() {}; //A function
aFunction.aProperty = " Property of function " ; //
aFunction.aMethod = function(){alert( " Method of function " )}; //Function
//See mainly the following:
alert(aFunction[ " aProperty " ]); //The
property can be accessed by the function as an array with the property name as a subscript aFunction[ " aMethod " ](); //A function can call a method
when the array has the square name as its index for( var s in aFunction) //All properties and methods of the traversal function are iterated
alert(s + " is a " + typeof(aFunction[s]));


/**
 * Yes, objects and functions can be accessed and processed as arrays, using property or method names as subscripts.
 * So, is it an array or an object? As we know, arrays should be considered as linear data structures, and linear data structures generally have certain rules, which are suitable for unified batch iterative operations, etc., kind of like waves.
 * Objects, on the other hand, are discrete data structures, suitable for describing discrete and personalized things, somewhat like particles.
 * So we can also ask: JavaScript Is the object a wave or a particle? If object quantum theory exists, the answer must be wave-particle duality!
 * As a result, JavaScript The functions and objects in the array have the characteristics of both objects and arrays. The array here is called a "dictionary," a collection of name-value pairs that can be scaled arbitrarily. In fact, object and function The internal implementation of the dictionary structure is a dictionary structure, but this kind of dictionary structure shows the rich appearance through the rigorous and exquisite syntax. Just as quantum mechanics USES particles in some places Explain and deal with problems, whereas in other places they are explained and dealt with in terms of waves. You also have the freedom to use objects or arrays to explain and handle problems as needed. As long as you're good at it JavaScript With these wonderful features, you can write a lot of simple and powerful code.
 */

Clicking on the margin triggers an element to close/hide


/**
 * Sometimes the page has a drop-down menu or something that needs to be hidden when the user clicks on a space or clicks on another element
 * You can use a global document Click on the event to trigger
 * @param {Object} " The target object "
 */
$(document).click(function(e){
    $(" The target object ").hide();
});
/**
 * One drawback is that you want the element to show up when you click on it
 * If you do not promptly prevent the event from bubbling to the overall departure document When the object is clicked, the above method executes
 */
$(" The target object ").click(function(event){
    event = event || window.event;
    event.stopPropagation(); //When the target object is clicked, prevent the event from bubbling
    $(" The target object ").toggle();
});

Above is a personal arrangement of some commonly used javascript methods, written down for the convenience of their own development directly to use, here is also recommended for the need of a partner.


Related articles: