In this post, we will share some less known but powerful JavaScript tips which can benefit both novice and veteran JavaScript developers.
1. Truncate array with array length
We all know that object are passed by reference in JavaScript, but we may be bitten by this rule. Please check below example:
| |
arr1 and arr2 point to the same array [1,2,3] initially, later when arr1 repoints to [], the reference to arr2 is not changed, it will still point to [1,2,3]. But if we want both arr1 and arr2 point to [], what should we do? We can use the length property of the array. When we set arr1.length=0, the elements in arr1 will be cleared. While the reference is not changed. So arr1 and arr1 point to [].
2. Merge array with push
We are used to use concat() to merge two arrays. For example:
| |
We can achieve this with push() as well:
| |
The apply method can take an array as the second argument, so arr2 can be pushed to arr1.
3. Feature detection
In many APIs, we can see some feature detection statements which will check whether the browser supports the specified property or method in order to support cross browser compatibility. We may have:
if(window.opera){
console.log("OPERA");
}else{
console.log("NOT OPERA");
}
This works correctly, but it may not be so efficient. This kind of object detection will initialize resources in the browser. The more efficient way is to check whether the key is in an object.
if("opera"inwindow){
console.log("OPERA");
}else{
console.log("NOT OPERA");
}
4. Check whether an object is an array
In JavaScript, we can use typeof to check type of a variable. typeof can return number, boolean, string, object, function and undefined. There is no array. In fact, typeof an array is object. So how can we determine whether an object is an array? In ECMAScript 5, we can use Array.isArray(obj) to check this. But ECMAScript 5 is not widely adopted as of now.
Actually we can use below method:
varobj=[];
Object.prototype.toString.call(obj)=="[object Array]";
true