JavaScript tips both novice and veteran develop...

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:


vararr1 = arr2 = [1, 2, 3];
 
//Change arr1
arr1 = [];// arr2 will still be [1,2,3]

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:

vararr1=[1,2,3];
vararr2=[4,5,6];
vararr3=arr1.concat(arr2);
arr3;
[1, 2, 3, 4, 5, 6]


We can achieve this with push() as well:

vararr1=[1,2,3];
vararr2=[4,5,6];
Array.prototype.push.apply(arr1,arr2);
arr1
[1, 2, 3, 4, 5, 6]


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

转载于:https://my.oschina.net/xiang1987/blog/159634

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值