Some less commonly used but powerful JavaScript tips that both novice and veteran js developers may not know.
1. Truncate arrays and array lengths
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
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
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3=arr1.concat(arr2);
alert(arr3)
arr3 becomes
[1, 2, 3, 4, 5, 6]
In fact, you can also use one A simple way is to use
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
if(window.opera){
alert("is opera")
}else{
alert("not opera")
}
Similarly, you can also do this
if("opera" in window){
alert("Yes opera")
}else{
alert("not opera")
}
4. The object checked is an array
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
var obj="fwe ";
if(Object.prototype.toString.call(obj)=="[object String]")
alert("is a string");
else
alert("is not a character string");