js Array vs [],以及是否為空的判斷


兩者基本相同,唯一不同點在於初始化:

var a = [],            // these are the same
b = new Array(),   // a and b are arrays with length 0

c = ['foo', 'bar'],           // these are the same
d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

// these are different:
e = [3]             // e.length == 1, e[0] == 3
f = new Array(3),   // f.length == 3, f[0] == undefined

也就是說Array(arg),其中的arg是指生成數組的長度。

參考:What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

 

檢查array是否為空:

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM