This chapter does not explain some underlying principles of js in depth, such as this pointer, scope, and prototype. It involves some of them that are conducive to simplifying code and improving execution efficiency during development, or they can be used as an empirical method. The length is not long, and small steps allow you to read the entire article and experience the joy of programming.
Get random numbers within two intervals
The code copy is as follows:
function getRandomNum(Min, Max){ // Get random numbers within two intervals
// @南南南南南南 suggests that the first parameter is greater than the second parameter, so adding a judgment is more reliable
if (Min > Max)
Max = [Min, Min = Max][0]; // Quickly exchange two variable values
var Range = Max - Min + 1;
var Rand = Math.random();
return Min + Math.floor(Rand * Range);
};
Return a positive/negative parameter randomly
The code copy is as follows:
function getRandomXY(num){ // Return a random positive/negative parameter
num = new Number(num);
if (Math.random() <= 0.5)
num = -num;
return num;
}
SetInterval() or setTimeOut() timer function pass parameter
The code copy is as follows:
var s = 'I am a parameter';
function fn(args) {
console.log(args);
}
var a = setInterval(fn(s),100); // xxxxx error xxxxxx
var b = setInterval(function(){ // Correct, call the timed function with anonymous function
fn(s);
}, 100);
setInterval() or setTimeOut() timer recursively called
The code copy is as follows:
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, which can be passed on seat parameters
}, 100);
Convert string to number
The code copy is as follows:
// No need for new Number(String) nor Number(String) Just subtract zeros from the string
var str = '100'; // str: String
var num = str - 0;// num: Number
Null value judgment
The code copy is as follows:
var s = ''; // Empty string
If(!s) // The empty string is converted to Boolean false by default, and can be written directly in the judgment statement
if(s != null) // But empty string!= null
if(s != undefined) // Empty string is also!= undefined
IE browser parseInt() method
The code copy is as follows:
// The following conversion is 0 in IE, and other browsers are 1. This is related to the IE browser's explanation of the digits.
var iNum = parseInt(01);
// So, the compatible writing is
var num = parseInt(new Number(01));
Firebug conveniently debug js code
The code copy is as follows:
//Firebug has a built-in console object, providing built-in methods to display information
/**
* 1:console.log(), which can be used instead of alert() or document.write(), supports placeholder output, characters (%s), integers (%d or %i), floating point numbers (%f) and objects (%o). For example: console.log("%d year %d month %d day", 2011, 3, 26)
* 2: If there is too much information, you can display it in groups. The methods used are console.group() and console.groupEnd()
* 3: console.dir() can display all properties and methods of an object
* 4: console.dirxml() is used to display the html/xml code contained in a node of a web page
* 5: console.assert() assert, used to determine whether an expression or variable is true
* 6: console.trace() is used to track the call track of the function
* 7: console.time() and console.timeEnd() are used to display the code's running time
* 8: Performance analysis (Profiler) is to analyze the running time of each part of the program to find out the bottleneck. The method used is console.profile()....fn....console.profileEnd()
*/
Quickly take the current milliseconds
The code copy is as follows:
// t == The current system millisecond value, reason: the + sign operator will be called, and the valueOf() method of Date will be called.
var t = +new Date();
Quickly take decimal integer bits
The code copy is as follows:
// x == 2, the following x values are 2, and negative numbers can also be converted
var x = 2.00023 | 0;
// x = '2.00023' | 0;
Two variable values interchange (no intermediate amount )
The code copy is as follows:
var a = 1;
var b = 2;
a = [b, b=a][0]
alert(a+'_'+b) // The values of result 2_1, a and b have been swapped.
Logical or '||' operator
The code copy is as follows:
// b is not null:a=b, b is null:a=1.
var a = b || 1;
// The most common usage is to pass parameters for a plug-in method and obtain event target elements: event = event || window.event
// IE has a window.event object, but FF does not.
Only the method object has prototype properties
The code copy is as follows:
// The method has the object prototype prototype property, while the original data does not have this property, such as var a = 1, a does not have a prototype property
function Person() {} // human constructor
Person.prototype.run = function() { alert('run...'); } // Prototype run method
Person.run(); // error
var p1 = new Person(); // The prototype run method will be assigned to p1 only when the new operator is used.
p1.run(); // run...
Quickly get the day of the week
The code copy is as follows:
// The current time of the calculation system is the week
var week = "Today is: week" + "Day One, Two, Three, Four, Five, Six".charat(new date().getDay());
Closure bias
The code copy is as follows:
/**
* Closure: Any js method body can be called a closure, not only does it happen if an inline function refers to a certain parameter or property of an external function.
* It has an independent scope, in which several subscopes can exist (i.e. method nested methods), and finally the closure scope is the scope of the outermost method.
* It contains the method parameters of the itself and the method parameters of all embedded functions. Therefore, when an embedded function has a reference externally, the scope of the reference is the (top-level) method scope where the reference function is located.
*/
function a(x) {
function b(){
alert(x); // Reference external function parameters
}
return b;
}
var run = a('run...');
// Due to the expansion of scope, variables of external function a can be referenced and displayed
run(); // alert(): run..
Get address parameter string and timed refresh
The code copy is as follows:
// Get a question mark? The following content includes the question mark
var x = window.location.search
// Get the content behind the alarm number #, including the # number
var y = window.location.hash
// Automatic web page refresh can be achieved with timer
window.location.reload();
Null and Undefined
The code copy is as follows:
/**
* The Undefined type has only one value, that is, undefined. When the declared variable has not been initialized, the default value of the variable is undefined.
* The Null type also has only one value, i.e. null. null is used to represent an object that has not existed yet, and is often used to represent a function that attempts to return an object that does not exist.
* ECMAScript believes that undefined is derived from null, so they are defined as equal.
* But, if in some cases we must distinguish between these two values, what should we do? The following two methods can be used
* When making judgments, it is best to use '===' strong type judgment when judging whether the object has a value according to needs.
*/
var a;
alert(a === null); // false, because a is not an empty object
alert(a === undefined); // true, because a is not initialized, the value is undefined
// Introduce
alert(null == undefined); // true, because the '==' operator will perform type conversion,
// Similarly
alert(1 == '1'); // true
alert(0 == false); // true, false converts to Number type 0
Dynamically add parameters to the method
The code copy is as follows:
// Method a has one more parameter 2
function a(x){
var arg = Array.prototype.push.call(arguments,2);
alert(arguments[0]+'__'+arguments[1]);
}
Customize SELECT border style
The code copy is as follows:
<!-- Copy to the page to try the effect, you can customize the style at will -->
<span style="border:1px solid red; position:absolute; overflow:hidden;" >
<select style="margin:-2px;">
<option>Custom SELECT border style</option>
<option>222</option>
<option>333</option>
</select>
</span>
The easiest color palette
The code copy is as follows:
<!-- JS to extract its value value and set any color to any object-->
<input type=color />
Functions, objects is array?
The code copy is as follows:
var anObject = {}; // an object
anObject.aProperty = "Property of object"; //A property of the object
anObject.aMethod = function(){alert("Method of object")}; //A method of the object
//Focus on the following:
alert(anObject["aProperty"]); //You can access the attribute as an array with the attribute name as a subscript
anObject["aMethod"](); //You can call a method as an array with the method name as a subscript
for( var s in anObject) //Transfer all properties and methods of the object for iterative processing
alert(s + ” is a ” + typeof(anObject[s]));
// It is the same for object of function type:
var aFunction = function() {}; //A function
aFunction.aProperty = "Property of function"; //A property of the function
aFunction.aMethod = function(){alert("Method of function")}; //A method of function
//Focus on the following:
alert(aFunction["aProperty"]); //You can access the properties as the array with the attribute name as the subscript
aFunction["aMethod"](); //You can call a method using the method name as a subscript when a function is used as a subscript for an array
for( var s in aFunction) //Iterate all properties and methods of the traversal function for iterative processing
alert(s + ” is a ” + typeof(aFunction[s]));
The code copy is as follows:
/**
* Yes, objects and functions can be accessed and processed like arrays, using attribute names or method names as subscripts.
* So, should it be considered an array or an object? We know that arrays should be considered linear data structures. Linear data structures generally have certain rules, which are suitable for unified batch iteration operations, etc., which is a bit like waves.
* Objects are discrete data structures that are suitable for describing scattered and personalized things, a bit like particles.
* Therefore, we can also ask: Are objects in JavaScript waves or particles? If there is object quantum theory, then the answer must be: wave-particle duality!
* Therefore, functions and objects in JavaScript have both the characteristics of objects and arrays. The array here is called a "dictionary", a collection of name-value pairs that can be arbitrarily stretched and condensed. In fact, the internal implementation of object and function is a dictionary structure, but this dictionary structure shows a rich appearance through rigorous and exquisite grammar. Just as quantum mechanics uses particles to explain and deal with problems in some places, while waves to explain and deal with problems in others. You can also freely choose to use objects or arrays to explain and deal with problems when needed. As long as you are good at grasping these wonderful features of JavaScript, you can write a lot of concise and powerful code.
*/
Clicking on a blank area can trigger an element to close/hide
The code copy is as follows:
/**
* Sometimes the page has a drop-down menu or something, which requires the user to hide it when clicking on a blank or clicking on other elements.
* A global document click event can be triggered
* @param {Object} "Target Object"
*/
$(document).click(function(e){
$("target object").hide();
});
/**
* But one disadvantage is that when you click on the element and want it to display it
* If you do not prevent the event from bubbled up to the global document object clicking in time, the above method will be executed
*/
$("Target Object").click(function(event){
event = event || window.event;
event.stopPropagation(); // When clicking on the target object, prevent the event from bubbled in time
$("Target Object").toggle();
});
The above are some commonly used javascript methods compiled by me. They can be recorded and used directly during development. This is also recommended for friends in need.