[英]Why Array.length does not work with key string
我一直在閱讀並做一些測試,發現了這個命令。 當數組的鍵是字符串時,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');
在數組上使用字符串“indexers”時,您實際上將其視為對象而不是數組,並將額外字段添加到該對象上。 如果您沒有使用整數索引,那么使用Array類型並沒有多大意義,而使用Object類型更有意義。 您可以按如下方式計算字段:
var c=0;
for(var fieldName in obj)
{
c++;
}
由於具有鍵字符串的數組是對象 ,因此您可以使用:
Object.keys(objElementos).length
原因是因為當你使用字符串作為鍵時,你實際上是在聲明一個對象,而不是一個數組。 因此,對象沒有長度屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.