为什么Array.length不能与键字符串一起使用

时间:2010-07-02 12:05:17

标签: arrays javascript

我一直在阅读并做一些测试,发现了这个命令。当数组的键是字符串时,Array()javascript的“长度”不起作用。我发现要运行此命令,我使用整个键。

然而,我想知道你们有没有人能告诉我为什么这条规则?语言的限制,还是逻辑的规范?或者,我的错误......?

由于

Obs。:我的数组的关键是一个字符串(组件名称),但是值和对象数组。

Declarating:

objElementos = new Array();

对象:

objElemento = function(Id){
this.Id        = $('#' + Id).attr('id');
this.Name      = $('#' + Id).attr('name');
this.CssLeft   = $('#' + Id).css('left');
this.CssBottom = $('#' + Id).css('bottom');
this.Parent    = $('#' + Id).parent().get(0);
this.Childs    = new Array();

this.addChild = function(IdObjChild) {
    try {
        if ($('#' + IdObjChild).attr('id') != '')
            this.Childs[$('#' + IdObjChild).attr('id')] = new objElemento(IdObjChild);
    } catch(err){ $('#divErrors').prepend('<p>' + err + '</p>'); }
}

this.getChildCount = function(){
    try {
        $('#divErrors').prepend('<p>' + this.Childs.length + '</p>');
        return this.Childs.length;
    } catch(err){ $('#divErrors').prepend('<p>' + err + '</p>'); }
}

this.updateCssLeft = function(CssPosition){
    try {
        $('#divErrors').prepend('<p>updateCssLeft:' + this.Id + ' / ' + this.CssLeft + '</p>');

        $('#' + this.Id).css('left',CssPosition);
        this.CssLeft = $('#' + this.Id).css('left');

        $('#divErrors').prepend('<p>updateCssLeft:' + this.Id + ' / ' + this.CssLeft + '</p>');         
    } catch(err){ $('#divErrors').prepend('<p>' + err + '</p>'); }
}

this.updateCssBottom = function(CssPosition){
    try {
        $('#divErrors').prepend('<p>updateCssBottom:' + this.Id + ' / ' + this.CssBottom + '</p>');

        $('#' + this.Id).css('bottom',CssPosition);
        this.CssBottom = $('#' + this.Id).css('bottom');

        $('#divErrors').prepend('<p>updateCssBottom:' + this.Id + ' / ' + this.CssBottom + '</p>');
    } catch(err){ $('#divErrors').prepend('<p>' + err + '</p>'); }
}
  }

使用:

objElementos['snaptarget'] = new objElemento('snaptarget');

3 个答案:

答案 0 :(得分:6)

在数组上使用字符串“indexers”时,您实际上将其视为对象而不是数组,并将额外字段添加到该对象上。如果您没有使用整数索引,那么使用Array类型并没有多大意义,而使用Object类型更有意义。您可以按如下方式计算字段:

var c=0;
for(var fieldName in obj)
{
    c++;
}

答案 1 :(得分:1)

由于具有键字符串的数组是对象,因此您可以使用:

Object.keys(objElementos).length

答案 2 :(得分:0)

原因是因为当您使用字符串作为键时,您实际上是在声明一个对象,而不是一个数组。因此,对象没有长度属性。

相关问题