简体   繁体   English

如何获得 javascript“数组”的长度

[英]how to get length of javascript "array"

We have been using javascript "hashes" a lot lately, and we've been looking for a universal way to count the items contained in both arrays and hashes without having to "know" which we're dealing with except in the count method.我们最近一直在使用 javascript“散列”,我们一直在寻找一种通用的方法来计算 arrays 和散列中包含的项目,而不必“知道”我们正在处理的项目,除了在 count 方法中。 As everyone knows.length is useless since it only returns the value of the highest index in the array.众所周知,length 是无用的,因为它只返回数组中最高索引的值。 What we have below does not work because hashes test true for Array, but the length value returned is crap for hashes.我们下面的内容不起作用,因为散列对数组测试为真,但返回的长度值对散列来说是垃圾。 We originally replaced.length all over our project with Object.keys().length, but this isn't supported in IE8 and lower.我们最初将整个项目的 .length 替换为 Object.keys().length,但这在 IE8 及更低版本中不受支持。

This is such a stupid simple thing and we can't seem to get it working.这是一件非常愚蠢的简单事情,我们似乎无法让它发挥作用。 Help me, Obi Wan.帮帮我,欧比旺。 You're my only hope!你是我唯一的希望!

function isNullOrUndefined(aObject) {
    "use strict";
    return (typeof aObject === 'undefined' || aObject === null);
}

function count(aList) {
    "use strict";
    var lKey = null,
        lResult = 0;
    if (!isNullOrUndefined(aList)) {
        if (aList.constructor == Array) {
            lResult = aList.length;
        } else if (!isNullOrUndefined(Object.keys)) {
            lResult = Object.keys(aList).length;
        } else {
            for (lKey in aList) {
                if (aList.hasOwnProperty(lKey)) {
                    lResult++;
                }
            }
        }
    }
    return lResult;
}

Object.keys polyfill copied verbatim from the ES5-shim Object.keysES5-shim逐字复制

// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
    // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
    var hasDontEnumBug = true,
        dontEnums = [
            "toString",
            "toLocaleString",
            "valueOf",
            "hasOwnProperty",
            "isPrototypeOf",
            "propertyIsEnumerable",
            "constructor"
        ],
        dontEnumsLength = dontEnums.length;

    for (var key in {"toString": null}) {
        hasDontEnumBug = false;
    }

    Object.keys = function keys(object) {

        if ((typeof object != "object" && typeof object != "function") || object === null) {
            throw new TypeError("Object.keys called on a non-object");
        }

        var keys = [];
        for (var name in object) {
            if (owns(object, name)) {
                keys.push(name);
            }
        }

        if (hasDontEnumBug) {
            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                var dontEnum = dontEnums[i];
                if (owns(object, dontEnum)) {
                    keys.push(dontEnum);
                }
            }
        }
        return keys;
    };

}

Despise the answer from Raynos that is completely valid please consider performance鄙视Raynos的回答是完全有效的请考虑性能

This is how my hash object look like这就是我的 hash object 的样子

function Hash(){
   this.values = [];
   this.keys = {};
}
Hash.prototype.set = function(key, val){ 
   if(this.keys[key]){
      this.values[this.keys[key]] = value
   }else{
      this.keys[key] = (this.values.push(val)-1)
   }
}
Hash.prototype.length = function(){
    return this.values.length
}

Why I do this is simple performance looping through an object to count the properties length will be really inefficient the solution above give you direct access all the time.为什么我这样做是简单的性能循环通过 object 来计算属性长度将非常低效上面的解决方案让您始终可以直接访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM