zoukankan      html  css  js  c++  java
  • Javascript 类数组对象

    第三方教程:

    https://segmentfault.com/a/1190000000415572
    http://www.jb51.net/article/59169.htm

    何为类数组?

    么是类数组对象:它首先是一个对象,其次与数组相似,它拥有 length 属性,但却不能使用数组的方法(Array.prototype)。

    只要一个对象Object,拥有 length 属性,那它就是一个类数组对象。譬如:

    - document.getElementsByTagName()语句返回的就是一个类数组对象。

    - 在function中,function代码内的arguments变量也是一个类数组对象。

    var a = function () {
        console.log(arguments) // { '0': 1, '1': 2, '2': 3, '3': 4 }
        console.log(arguments.length) // 4
    }
    
    a(1, 2, 3, 4)

    自定义类数组对象,但是对象的 key 必须是 Number 类型。

    var a = {
        '0':'a',
        '1':'b',
        '2':'c',
        length:3
    };

    像数组一样使用类数组

    之所以成为“类数组”,就是因为和“数组”类似。不能直接使用数组方法,但你可以像使用数组那样,使用类数组。

    var likeArrayObject = {
        '0':'a',
        '1':'b',
        '2':'c',
        length:3
    };
    
    // 转为数组
    Array.prototype.slice.call( likeArrayObject ); // [ 'a', 'b', 'c' ]
    
    // 取出第一位
    Array.prototype.shift.call( likeArrayObject ) // a
    
    // 数组转为字符串累加
    Array.prototype.join.call( likeArrayObject, ' + ' ); // a + b + c
    
    // 使用数组的map遍历方法,逐个转化为大写并且返回到新数组中
    Array.prototype.map.call( likeArrayObject, function(x) { return x.toUpperCase(); }); // [ 'A', 'B', 'C' ]


    类数组判断
    《javascript权威指南》上给出了代码用来判断一个对象是否属于“类数组”。如下:

    function isArrayLike(o) {
        if (o && // o is not null, undefined, etc.
            typeof o === 'object' && // o is an object
            isFinite(o.length) && // o.length is a finite number
            o.length >= 0 && // o.length is non-negative
            o.length === Math.floor(o.length) && // o.length is an integer
            o.length < 4294967296) // o.length < 2^32
            return true; // Then o is array-like
        else
            return false; // Otherwise it is not
    }
  • 相关阅读:
    虚拟化技术KVM
    Rsync+Inotify实现文件自动同步
    第一次使用博客园
    kmp算法分析
    程序可移植性分析(一)数据类型
    strings用法小记
    size用法小记
    readelf用法小记
    nm用法小记
    ar用法小记
  • 原文地址:https://www.cnblogs.com/CyLee/p/6511097.html
Copyright © 2011-2022 走看看