Home Web Front-end JS Tutorial Summary of javascript practical methods

Summary of javascript practical methods

May 16, 2016 pm 04:15 PM
javascript Practical methods

Introduction: This chapter does not provide a profound explanation of some of the underlying principles of js, such as this pointer, scope, and prototype. It involves some things that are beneficial to simplifying code and improving execution efficiency during daily development, or it can be used as an empirical method. Come and use it, the length is not long, you can read the entire article in small steps and experience the joy of programming.

Get random numbers within two intervals

function getRandomNum(Min, Max){ // 获取两个区间之内随机数
    // @逆火狂飙  提出有可能第一个参数大于第二个参数,所以增加一下判断更可靠
    if (Min > Max) 
    Max = [Min, Min = Max][0]; // 快速交换两个变量值
    
    var Range = Max - Min + 1;
    var Rand = Math.random();
    return Min + Math.floor(Rand * Range);
};
Copy after login

Randomly return a positive/negative parameter

function getRandomXY(num){ // 随机返回一个 正/负参数
    num = new Number(num);
    if (Math.random() <= 0.5) 
        num = -num;
    return num;
}
Copy after login

setInterval() or setTimeOut() timer function passing parameters

var s = &#39;我是参数&#39;;
function fn(args) {
    console.log(args);
}
var a = setInterval(fn(s),100);    // xxxxxx错误xxxxx
var b = setInterval(function(){    // 正确,用匿名函数调用被计时函数
    fn(s);
}, 100)
Copy after login

setInterval () or setTimeOut() timer recursively calls

var s = true;
function fn2(a, b){        //  步骤三
    if (s) {
        clearInterval(a);
        clearInterval(b);
    }
};
function fn(a){     //  步骤二
    var b = setInterval(function(){
        fn2(a, b) // 传入两个计时器
    }, 200)
};
var a = setInterval(function(){      //  步骤一
    fn(a); // b代表计时器本身,可座位参数传递
}, 100)
Copy after login

Convert string to number

// 无需 new Number(String)   也无需 Number(String) 只需字符串减去零即可
var str = &#39;100&#39;;  // str: String
var num = str - 0;// num: Number
Copy after login

Null value judgment

var s = &#39;&#39;;  // 空字符串
if(!s)         // 空字符串默认转换为布尔false,可以直接写在判断语句里面
if(s != null) // 但是空字符串 != null
if(s != undefined) // 空字符串也 != undefine
Copy after login

IE browser parseInt() method

// 下面的转换在IE下为0,其他浏览器则为1,这跟IE浏览器解释数字的进制有关
var iNum = parseInt(01);
// 所以,兼容的写法为
var num = parseInt(new Number(01))
Copy after login

Firebug is convenient for debugging js code

//Firebug内置一个console对象,提供内置方法,用来显示信息
/**
 * console.log(),可以用来取代alert()或document.write(),支持占位符输出,字符(%s)、整数(%d或%i)、浮点数(%f)和对象(%o)。如:console.log("%d年%d月%d日",2011,3,26)
 * 如果信息太多,可以分组显示,用到的方法是console.group()和console.groupEnd()
 * console.dir()可以显示一个对象所有的属性和方法
 * console.dirxml()用来显示网页的某个节点(node)所包含的html/xml代码
 * console.assert()断言,用来判断一个表达式或变量是否为真
 * console.trace()用来追踪函数的调用轨迹
 * console.time()和console.timeEnd(),用来显示代码的运行时间
 * 性能分析(Profiler)就是分析程序各个部分的运行时间,找出瓶颈所在,使用的方法是:
       console.profile()....fn....console.profileEnd()
 */
Copy after login
Quickly get the current time in milliseconds
// t == 当前系统毫秒值,原因:+号运算符会,会调用Date的valueOf()方法。
var t = +new Date();
Copy after login

Quickly get decimal places

// x == 2,以下x值都为2,负数也可转换
var x = 2.00023 | 0;
// x = &#39;2.00023&#39; | 0
Copy after login

Interchange the values ​​of two variables (without intermediate amounts)

var a = 1;var b = 2;a = [b, b=a][0]alert(a+&#39;_&#39;+b)    // 结果 2_1,a和b的值已经互换。
Copy after login

Logical OR '||' operator

// b不为null:a=b, b为null:a=1。
var a = b || 1;
// 较常见的用法为为一个插件方法传参,和获取事件目标元素:event = event || window.event
// IE有window.event对象,而FF没有
Copy after login

Only method objects have prototype prototype attributes

// 方法有对象原型prototype属性,而原始数据没有该属性,如  var a = 1, a没有prototype属性
function Person() {} // 人的构造函数
Person.prototype.run = function() { alert(&#39;run...&#39;); } // 原型run方法
Person.run(); // error
var p1 = new Person(); // 只有在new操作符时,此时才会把原型run方法赋值给p1
p1.run(); // run..
Copy after login

Quickly get the day of the week

// 计算系统当前时间是星期几
var week = "今天是:星期" + "日一二三四五六".charat(new date().getDay())
Copy after login

Closure bias

/** * 闭包:任何一个js方法体都可以称为一个闭包,并非什么只有内嵌函数来引用了外部函数的某个参数或属性才会发生。 
* 它有一个独立作用域,在该作用域内可存在若干的子作用域(就是方法嵌套方法),最终该闭包作用域为最外层方法的作用域 
* 它包含了本身方法参数和所有内嵌函数的方法参数,所以当一个内嵌函数在外部有引用时,该引用的作用域为引用函数所在的(顶级)方法作用域 
*/ 
function a(x) {    
   function b(){        
      alert(x); // 引用外部函数参数    
   }    
   return b;
}
var run = a(&#39;run...&#39;); 
// 由于作用域的扩大,可以引用到外部函数a的变量并显示run(); 
// alert(): run..
Copy after login

Get address parameter string and refresh regularly

// 获取问号?后面的内容,包括问号
var x = window.location.search
// 获取警号#后面的内容,包括#号
var y = window.location.hash
// 配合定时器可实现网页自动刷新
window.location.reload()
Copy after login

Null and Undefined

/**
 * Undefined类型只有一个值,即undefined。当声明的变量还未被初始化时,变量的默认值为undefined。
 * Null类型也只有一个值,即null。null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象。
 * ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。
 * 但是,如果在一些情况下,我们一定要区分这两个值,那应该怎么办呢?可以使用下面的两种方法
 * 在进行判断时根据需要,判断对象是否有值时最好用‘===&#39;强类型判断。
 */
var a;
alert(a === null); // false,因为a不是一个空对象
alert(a === undefined); // true,因为a未初始化,值为undefined
// 引申
alert(null == undefined); // true,因为‘==&#39;运算符会进行类型转换,
// 同理
alert(1 == &#39;1&#39;); // true
alert(0 == false); // true,false转换为Number类型为0
Copy after login

Dynamically add parameters to the method

// 方法a多了一个参数2
function a(x){
    var arg = Array.prototype.push.call(arguments,2);
    alert(arguments[0]+&#39;__&#39;+arguments[1]);
Copy after login

Function, object is array?

var anObject = {}; //一个对象
anObject.aProperty = “Property of object”; //对象的一个属性
anObject.aMethod = function(){alert(“Method of object”)}; //对象的一个方法
//主要看下面:
alert(anObject[“aProperty”]); //可以将对象当数组以属性名作为下标来访问属性
anObject[“aMethod”](); //可以将对象当数组以方法名作为下标来调用方法
for( var s in anObject) //遍历对象的所有属性和方法进行迭代化处理
alert(s + ” is a ” + typeof(anObject[s]));
// 同样对于function类型的对象也是一样:
var aFunction = function() {}; //一个函数
aFunction.aProperty = “Property of function”; //函数的一个属性
aFunction.aMethod = function(){alert(“Method of function”)}; //函数的一个方法
//主要看下面:
alert(aFunction[“aProperty”]); //可以将函数当数组以属性名作为下标来访问属性
aFunction[“aMethod”](); //可以将函数当数组以方法名作为下标来调用方法
for( var s in aFunction) //遍历函数的所有属性和方法进行迭代化处理
alert(s + ” is a ” + typeof(aFunction[s]));
Copy after login
/**
 * 是的,对象和函数可以象数组一样,用属性名或方法名作为下标来访问并处理。
 * 那么,它到底应该算是数组呢,还是算对象?我们知道,数组应该算是线性数据结构,线性数据结构一般有一定的规律,适合进行统一的批量迭代操作等,有点像波。
 * 而对象是离散数据结构,适合描述分散的和个性化的东西,有点像粒子。
 * 因此,我们也可以这样问:JavaScript 里的对象到底是波还是粒子?如果存在对象量子论,那么答案一定是:波粒二象性!
 * 因此,JavaScript里的函数和对象既有对象的特征也有数组的特征。这里的数组被称为“字典”,一种可以任意伸缩的名称值对儿的集合。其实, object和function的内部实现就是一个字典结构,但这种字典结构却通过严谨而精巧的语法表现出了丰富的外观。正如量子力学在一些地方用粒子来 解释和处理问题,而在另一些地方却用波来解释和处理问题。你也可以在需要的时候,自由选择用对象还是数组来解释和处理问题。只要善于把握 JavaScript 的这些奇妙特性,就可以编写出很多简洁而强大的代码来。
 */
Copy after login

Clicking on a blank space can trigger a certain element to close/hide

/**
 * 有时候页面有个下拉菜单或者什么的效果,需要用户点击空白处或者点击其他元素时将其隐藏
 * 可用一个全局document点击事件来触发
 * @param {Object} "目标对象"
 */
$(document).click(function(e){
    $("目标对象").hide();
});
/**
 * 但是有一个缺点就是当你点击该元素又想让他显示
 * 如果你不及时阻止事件冒泡至全局出发document对象点击时,上面方法就会执行
 */
$("目标对象").click(function(event){
    event = event || window.event;
    event.stopPropagation(); // 当点击目标对象时,及时阻止事件冒泡
    $("目标对象").toggle();
});
Copy after login

The above are some commonly used javascripts that I have summarized Here’s the method, I hope you all like it. For more related tutorials, please visit JavaScript Video Tutorial!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles