Home Web Front-end JS Tutorial Summary of JavaScript programming learning skills_javascript skills

Summary of JavaScript programming learning skills_javascript skills

May 16, 2016 pm 03:14 PM
javascript study skills

The examples in this article share JavaScript programming learning skills for your reference. The specific content is as follows

1. Variable conversion

varmyVar="3.14159",

str=""+myVar,//tostring

int=~~myVar,//tointeger

float=1*myVar,//tofloat

bool=!!myVar,/*toboolean-anystringwithlength

andanynumberexcept0aretrue*/

array=[myVar];//toarray
Copy after login

However, you must use the constructor to convert dates (new Date(myVar)) and regular expressions (new RegExp(myVar)). When creating regular expressions, use simplified forms such as /pattern/flags.

2. Round and convert to numerical value at the same time

//字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)

'10.567890'|0

//结果:10

//JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算

//|是二进制或,x|0永远等于x;^为异或,同0异1,所以x^0还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的

'10.567890'^0

//结果:10

-2.23456789|0

//结果:-2
Copy after login

3. Convert date to value

//JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位

vard=+newDate();//1295698416792

Copy after login

4. Convert array-like object to array

vararr=[].slice.call(arguments)

下面的实例用的更绝

functiontest(){

varres=['item1','item2']

res=res.concat(Array.prototype.slice.call(arguments))//方法1

Array.prototype.push.apply(res,arguments)//方法2

}

Copy after login

5. Conversion between bases

(int).toString(16);//convertsinttohex,eg12=>"C"

(int).toString(8);//convertsinttooctal,eg.12=>"14"

parseInt(string,16)//convertshextoint,eg."FF"=>255

parseInt(string,8)//convertsoctaltoint,eg."20"=>16

将一个数组插入另一个数组指定的位置

vara=[1,2,3,7,8,9];

varb=[4,5,6];

varinsertIndex=3;

a.splice.apply(a,Array.prototype.concat(insertIndex,0,b));

Copy after login

6. Delete array elements

vara=[1,2,3,4,5];

a.splice(3,1);//a=[1,2,3,5]

Copy after login

You may wonder why you should use splice instead of delete, because using delete will leave a hole in the array, and the subsequent subscripts will not be decremented.
7. Determine whether it is IE

varie=/*@cc_on!@*/false;
Copy after login

Such a simple sentence can determine whether it is ie, too. . .

In fact, there are more wonderful ways, please see below

//edithttp://www.lai18.com

//貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制

varie=!-[1,];

//利用了IE的条件注释

varie=/*@cc_on!@*/false;

//还是条件注释

varie//@cc_on=1;

//IE不支持垂直制表符

varie='v'=='v';

//原理同上
varie=!+"v1";
Copy after login

The moment I learned this, I felt weak.

Use native methods as much as possible

To find the maximum number in a set of numbers, we might write a loop, for example:

varnumbers=[3,342,23,22,124];

varmax=0;

for(vari=0;i

if(numbers[i]>max){

max=numbers[i];

}

}

alert(max);

Copy after login

In fact, it can be implemented more easily using native methods

varnumbers=[3,342,23,22,124];

numbers.sort(function(a,b){returnb-a});

alert(numbers[0]);

Copy after login

Of course the simplest method is:

Math.max(12,123,3,2,433,4);//returns433
Copy after login

This is also possible now

[xhtml]view plaincopy

Math.max.apply(Math,[12,123,3,2,433,4])//取最大值

Math.min.apply(Math,[12,123,3,2,433,4])//取最小值

Copy after login

8. Generate random numbers

Math.random().toString(16).substring(2);//toString()函数的参数为基底,范围为2~36。

Math.random().toString(36).substring(2);

Copy after login

Exchange the values ​​of two variables without using third-party variables

a=[b,b=a][0];
Copy after login

9. Event delegation

js code is as follows:

//Classiceventhandlingexample

(function(){

varresources=document.getElementById('resources');

varlinks=resources.getElementsByTagName('a');

varall=links.length;

for(vari=0;i

//Attachalistenertoeachlink

links[i].addEventListener('click',handler,false);

};

functionhandler(e){

varx=e.target;//Getthelinkthatwasclicked

alert(x);

e.preventDefault();

};

})();

Copy after login

Use event delegation to write more elegantly:

(function(){

varresources=document.getElementById('resources');

resources.addEventListener('click',handler,false);

functionhandler(e){

varx=e.target;//getthelinktha

if(x.nodeName.toLowerCase()==='a'){

alert('Eventdelegation:'+x);

e.preventDefault();

}

};

})();

Copy after login

10. Check ie version

var_IE=(function(){

varv=3,div=document.createElement('div'),all=div.getElementsByTagName('i');

while(

div.innerHTML='',

all[0]

);

returnv>4?v:false;

}());

Copy after login

javaScript version detection

Do you know which version of Javascript your browser supports?

varJS_ver=[];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;

([].indexOf&&[].forEach)?JS_ver.push("1.6"):false;

((function(){try{[a,b]=[0,1];returntrue;}catch(ex){returnfalse;}})())?JS_ver.push("1.7"):false;

([].reduce&&[].reduceRight&&JSON)?JS_ver.push("1.8"):false;

("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports=function()

{

if(arguments[0])

return(!!~this.join().indexOf(arguments[0]+",")+",");

else

return(this[this.length-1]);

}

alert("LatestJavascriptversionsupported:"+JS_ver.supports());

alert("Supportforversion1.7:"+JS_ver.supports("1.7"));

Copy after login

11. Determine whether the attribute exists

//BAD:Thiswillcauseanerrorincodewhenfooisundefined

if(foo){

doSomething();

}
//GOOD:Thisdoesn'tcauseanyerrors.However,evenwhen

//fooissettoNULLorfalse,theconditionvalidatesastrue

if(typeoffoo!="undefined"){

doSomething();

}
//BETTER:Thisdoesn'tcauseanyerrorsandinaddition

//valuesNULLorfalsewon'tvalidateastrue

if(window.foo){

doSomething();

}

Copy after login

Sometimes we have deeper structures and need more appropriate inspections

//UGLY:wehavetoproofexistenceofevery

//objectbeforewecanbesurepropertyactuallyexists

if(window.oFoo&&oFoo.oBar&&oFoo.oBar.baz){

doSomething();

}

Copy after login

In fact, the best way to detect whether an attribute exists is:

if("opera"inwindow){

console.log("OPERA");

}else{

console.log("NOTOPERA");

}

Copy after login

12. Check whether the object is an array

varobj=[];

Object.prototype.toString.call(obj)=="[objectArray]";
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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 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

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.

Easily learn to type full-width symbols on your keyboard! Easily learn to type full-width symbols on your keyboard! Mar 26, 2024 am 09:57 AM

Typing symbols on a computer keyboard is something we often encounter when using computers on a daily basis. Most of the time, the symbols we use are half-width symbols, which are English symbols, such as ",", ".", and "!". But sometimes we also need to use full-width symbols, such as Chinese symbols ",", ".", "!". Full-width symbols will be more beautiful when typesetting, making the text look more Chinese-style. Today we will learn how to enter full-width symbols on the keyboard to make your documents look more professional and standardized. First, let us understand a

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

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

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