12個很是有用的javascript技巧,必看!

提示:該文章是整理別人別人的文章,做者比較多,很難分辨原創做者是誰。正則表達式

1)使用!!將變量轉換成布爾類型數組

  有時,咱們須要檢查一些變量是否存在,或者它是否具備有效值,從而將他們的值視爲true。對於這樣的檢查,你可使用!!(雙重否認運算符),他能自動將任何類型的數據轉化爲布爾值,只有0、null、「」、undefined或NaN纔會返回false,其餘的都會返回true。看一個簡單的例子:瀏覽器

function Account(cash){
    this.cash = cash;
    this.hasMoney = !!cash;
}
   var account = new Account(100.50);
   console.log(account.cash);        //100.50
   console.log(account.hasMoney);    //true
    
   var emptyAccount = new Account(0);
   console.log(emptyAccount.cash);        //0
   console.log(emptyAccount.hasMoney);  //false

2)使用+將變量轉化成數字緩存

  這個轉化比較簡單,但它只適合數字字符串,否則就會返回NaN(Not a Number)。看例子:app

function toNumber(strNumber){
    return +strNumber;
}
console.log(toNumber('342')); //342
console.log(toNumber('324s')); //NaN
//也能夠用於轉化Date,返回結果爲時間戳
console.log(+new Date());

3)短路條件dom

  在編寫代碼中常常會遇到這樣的代碼:函數

  

if(conected){
    login();
}

  可使用&&(and鏈接符)來縮短代碼,上面的代碼能夠縮減爲性能

  conected&&login();測試

  也可使用這種方法來檢查對象中是否存在某些屬性或者方法this

  user&&user.login();

4)使用||設置默認值

  在ES6中有默認參數這個功能。爲了在舊版瀏覽器中模擬此功能,可以使用||(or運算符),並把默認值做爲他的第二個參數。若是第一個參數返回false,那麼第二個參數就會被做爲默認值返回

 

function user(name,age){
    this.name = name||'Olive Queen';
    this.age = age||27;
}

var user1 = new user();
console.log(user1.name);//Olive Queen
console.log(user1.age);//27

var user2 = new user('liming',25);
console.log(user2.name);//liming
console.log(user2.age);//25

5)在循環中緩存arr.length

  這個技巧很是簡單,而且在循環處理大數組時可以避免對性能形成巨大的影響。例如for循環

var arr = [1,2,3,'a','ds',4];
for(var i = 0;i<arr.length;i++){
    console.log(arr[i]);
}

對於小數組還好,較大數組的話每一次循環都會獲取arr.length,這會產生必定的延遲,爲了不這種狀況,在for循環開始以前緩存arr.length

var arr = [1,2,3,'a','ds',4];
var len = arr.length;
for(var i = 0;i<len;i++){
    console.log(arr[i]);
}

或者

var arr = [1,2,3,'a','ds',4];
for(var i = 0,len = arr.length;i<len;i++){
    console.log(arr[i]);
}

6)檢查對象中的屬性

  當你須要檢查某些屬性是否存在的時候,避免運行未定義的函數或者屬性時,這個技巧就會很是的有用。解決瀏覽器兼容問題中也可使用這個技巧。例如經過ID獲取元素的完美方法

if('querySelector' in document){
    document.querySelector('#id');
}else{
    document.getElementById('id');
}

7)獲取數組的最後一個元素

  Array.prototype.slice(begin,end)能夠用來裁剪數組。可是若是沒有設置結束參數end的值的話,該函數會自動將end設置爲數組長度值。若是將begin的數值設置爲複製的話,就會從數組中獲取倒數的元素:

var arr = [1,2,3,4,5];
console.log(arr.slice(-1));//[6]
console.log(arr.slice(-2));//[5,6]
console.log(arr.slice(-3));//[4,5,6]

8)數組截斷

  這個技術能夠鎖定數組的大小,這對於要刪除數組中固定數量的元素是很是有用的。

var arr = [1,2,3,4,5,6,7,8,9,10];

arr.length = 5;
console.log(arr);//[1,2,3,4,5]

arr.length = 7;
console.log(arr);//[1,2,3,4,5,undefined,undefined]

若是arr.length設置的數值大於當前數組長度,超過的元素會分配爲undefined

9)替換字符串某段元素

  String.replace()函數容許你使用字符串或正則表達式來替換字符串,自己這個函數只替換第一次出現的字符串,不過你可使用正則表達多中的/g來模擬replaceAll()函數功能:

var str = 'john john';
console.log(str.replace(/hn/,'nan'));//jonan john
console.log(str.replace(/hn/g,'nan'));//jonan jonan

10)合併數組

  通常須要合併數組,使用Array.concat()方法,字符串也能夠看作是數組

var str1 = 'hello';
var str2 = 'world';
console.log(str1.concat(str2));//helloworld
var str3 = [1,2,3];
var str4 = [4,5,6];
console.log(str3.concat(str4));//[1,2,3,4,5,6]

可是該方法對於大數組來講並不合適,由於他會在內部新建一個數組並消耗大量的內存。原做者推薦使用Array.push.apply(arr1,arr2),可是在實踐後發現其返回的結果始終是最後數組的長度,而不是數組的各個元素;並且有博主曾經作過Array.concat與Array.push.apply之間性能的測試實驗。結果顯示Array.concat操做的數組長度沒有顯示,而Array.oush.apply操做的數組因瀏覽器不一樣而不一樣,通常不能超過十萬。

腳本之家有位朋友寫過一篇《關於JS數組追加數組採用push.apply的問題》,討論Array.push.apply的問題,最後採用forEach,不只能夠避免數組過大的問題,並且從性能考慮forEach也是最快的。

var arr = [1,2,3,4,5,6,7,8,9];
arr.forEach(function(a){
    console.log(a);
});

可是在IE中該方法不能正常執行,提示Array不支持此屬性或此方法,即IE的Array中沒有forEach方法。可是能夠添加原型方法

    //Array.forEach implementation for IE support..  
    //https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach  
    if (!Array.prototype.forEach) {  
        Array.prototype.forEach = function(callback, thisArg) {  
            var T, k;  
            if (this == null) {  
                throw new TypeError(" this is null or not defined");  
            }  
            var O = Object(this);  
            var len = O.length >>> 0; // Hack to convert O.length to a UInt32  
            if ({}.toString.call(callback) != "[object Function]") {  
                throw new TypeError(callback + " is not a function");  
            }  
            if (thisArg) {  
                T = thisArg;  
            }  
            k = 0;  
            while (k < len) {  
                var kValue;  
                if (k in O) {  
                    kValue = O[k];  
                    callback.call(T, kValue, k, O);  
                }  
                k++;  
            }  
        };  
    }  

11)打亂數組內的元素

 

var list = [1,2,3,4.5,55];
var arr = list.sort(function(){
    return Math.random()-0.5;
});
console.log(arr);//[4.5,1,2,3,55]
console.log(arr[2]);//2

我暫時沒有發現這個技巧有什麼特別的用處,就只是打亂數組內的元素,生成的是一個新的數組。

12)將Nodelist轉換爲數組

  DOM操做document.querySelectorAll('p'),或者document.getElementsByTagName都會返回一個DOM元素數組,即Nodelist對象,可是這個對象並無一些屬於數組的函數,如sort()、reduce()、map()、filter()。爲了啓用這些函數,以及數組的其餘原生函數,須要將Nodelist轉化爲數組。這就要用到[].slice.call(elements)或者Array.from(elements)

var eles = document.querySelectorAll('div');
var arrEles = [].slice.call(eles);
//var arrEles = Array.from(eles); console.log(arrEles);
//[div.big,div#small]

返回的是元素的數組,div.big表示元素div的class爲big。

相關文章
相關標籤/搜索