There are some JavaScript tricks that no veteran knows about

  • 2020-03-30 02:51:30
  • OfStack

Some of the less commonly used but powerful JavaScript tips are not necessarily known to both novice and experienced js developers.

1. Truncate array and array length

var arr1 = arr2 = [1, 2, 3];

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

You'll notice that arr1 USES the [] method to clean up the arr2 without affecting the arr2 value, if you want arr2 to change with arr1

 var arr1 = arr2 = [1, 2, 3];
arr1.length=0; //Notice this step instead of arr1=[]
alert(arr2)

Arr2 is also cleared

2. Array merge


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

Arr3, into
[1 . 2 . 3 . 4 . 5 . 6]

Actually still can use a kind of simple method, for example use
var  arr1 = [1,2,3];
var  arr2 = [4,5,6];
Array.prototype.push.apply(arr1,arr2);
alert(arr1)

So arr1 becomes 1,2,3,4,5,6

3. Browser feature detection

Take a look at the code to see if your browser is opera or not

if(window.opera){
    alert(" is opera")
}else{
      alert(" not opera")
}

You can do the same thing
if("opera" in window){
     alert(" is opera")
}else{
   alert(" not opera")
}

4. The checked object is an array

 var obj=[];
 if(Object.prototype.toString.call(obj)=="[object Array]")
   alert(" Is an array ");
   else
    alert(" Is not an array ");

Again, you can determine if the object is a string
 var obj="fwe";
 if(Object.prototype.toString.call(obj)=="[object String]")
   alert(" Is the string ");
   else
    alert(" It's not a string ");
 


Related articles: