Home  >  Article  >  Web Front-end  >  Some JavaScript skills that veterans may not know_javascript skills

Some JavaScript skills that veterans may not know_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:49:43923browse

Some less commonly used but powerful JavaScript tips that both novice and veteran js developers may not know.

1. Truncate arrays and array lengths

Copy code The code is as follows:
var arr1 = arr2 = [1, 2, 3];

//Change arr1
arr1 = []; // arr2 is still [1,2,3]

You will find that using the [] method to clear arr1 will not affect the value of arr2. If you want arr1 to change and arr2 to change together, you can do this
Copy code The code is as follows:

var arr1 = arr2 = [1, 2, 3];
arr1.length=0; //Note This step is not arr1=[]
alert(arr2)

At this time arr2 is also cleared

2. Array merging

Copy code The code is as follows:

var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3=arr1.concat(arr2);
alert(arr3)

arr3 becomes
Copy code The code is as follows:
[1, 2, 3, 4, 5, 6]

In fact, you can also use one A simple way is to use
to copy the code The code is as follows:
var arr1 = [1,2,3 ];
var arr2 = [4,5,6];
Array.prototype.push.apply(arr1,arr2);
alert(arr1)

At this time arr1 becomes It became 1,2,3,4,5,6

3. Browser feature detection

Look at the code to determine whether your browser is opera

Copy the code The code is as follows:
if(window.opera){
alert("is opera")
}else{
alert("not opera")
}

Similarly, you can also do this
Copy code The code is as follows:
if("opera" in window){
alert("Yes opera")
}else{
alert("not opera")
}

4. The object checked is an array

Copy code The code is as follows:
var obj=[];
if(Object.prototype. toString.call(obj)=="[object Array]")
alert("is an array");
else
alert("is not an array");

Similarly, You can also determine whether the object is a string
Copy code The code is as follows:
var obj="fwe ";
if(Object.prototype.toString.call(obj)=="[object String]")
alert("is a string");
else
alert("is not a character string");
Statement:
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