javascript學習記錄-數組(8)-完結 2014/02/26

數組類型判斷


在ECMAScript5中,能夠使用Array.isArray()函數。 數組

Array.isArray([]);    // true
Array.isArray({});    // false

但在ECMAScript 3中,並無這樣的函數 函數


嘗試typeof spa

typeof([]);    // 'object',確定是不行了
typeof(new Array());    // 'object'


嘗試instanceof prototype

[] instanceof Array;    // true,可行
(new Array()) instanceof Array;    // true,可行
({}) instanceof Array;    // false


由於存在多窗口之間的混淆問題,不建議使用instanceof code

解決方案 對象

var isArray = Function.isArray || function(o) {
    return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]";
};


數組獨有的特色


  1. 新元素添加時,自動更新length屬性
  2. 設置length屬性小於元素實際數量時截斷數組
  3. 從Array.prototype中繼承一些有用的方法
  4. 類屬性爲「Array」


類數組對象


擁有一個數據length屬性和對應非負整數屬性的對象 繼承


  • 遍歷類數組對象
var a = {};    // {}

var i = 0;

while(i < 10) {
    a[i] = i * i;
    i++;
}

a.length = i;    // 爲對象a添加屬性length


對象a的構成以下 ip

{ '0': 0,
  '1': 1,
  '2': 4,
  '3': 9,
  '4': 16,
  '5': 25,
  '6': 36,
  '7': 49,
  '8': 64,
  '9': 81 } 字符串

以數組的方式遍歷對象a it

var total = 0;

for (var j = 0; j < a.length; j++) {

    total += a[j];

}

total     // 285


  • 檢測對象是不是類數組對象
function isArrayLike(o) {

    if ( o &&    // o非null、undefined等

        typeof o === 'object' &&    // o是對象

        isFinite(o.length) &&    // o.length是有限數值

        o.length > =0 &&    // o.length是非負數

        o.length === Math.floor(o.length) &&    // o.length是整數

        o.length < 4294967296)    // o.length < 2^32

            return true;

    else

        return false;

}


  • 調用數組的原生方法
var a = {"0": "a", "1": "b", "2": "c", length: 3};

Array.prototype.join.call(a, "+");    // 'a+b+c'

Array.prototype.slice.call(a, 0);    // [ 'a', 'b', 'c' ]

Array.prototype.map.call(a, function(x) {

    return x.toUpperCase();    

});

a    // [ 'A', 'B', 'C' ]


做爲數組的字符串


ECMAScript 5中類數組的字符串訪問

var s = "test";

s.charAt(0);    // t

s[1]    // e
類數組的字符串方法


var s = "JavaScript";

Array.prototype.join.call(s, " ");    // 'J a v a S c r i p t'

Array.prototype.filter.call(s, function(x) {

    return x.match(/[^aeiou]/);

}).join("");

x    // 'JvScrpt'


字符串是隻讀的,將數組的方法應用於字符串時,修改字符的處理會出錯。


Array.prototype.sort(s);    // [],無效
相關文章
相關標籤/搜索