【问题标题】:Find length (size) of an array in JavaScript在 JavaScript 中查找数组的长度(大小)
【发布时间】:2011-07-16 02:17:08
【问题描述】:

我想我快疯了。出于某种原因,我有一个很简单的问题。

为什么下面会返回'undefined'?

var testvar={};
testvar[1]=2;
testvar[2]=3;
alert(testvar.length);

edit 我最初输入的是 testvar[1].length。我知道这是一个错误。我的意思是 testvar.length

【问题讨论】:

  • 你想完成什么?您期望结果是什么?

标签: javascript arrays


【解决方案1】:

因为2 不是一个数组,它是一个数字。数字没有长度。

也许你的意思是写testvar.length;这也是未定义的,因为对象(使用{ ... } 表示法创建)没有长度。

只有数组有长度属性:

var testvar = [  ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length);    // 3

请注意,Javascript 数组的索引从 0 开始,不一定是 sparse(因此结果是 3 而不是 2 - 请参阅 this answer 了解数组何时稀疏以及何时稀疏不会)。

【讨论】:

    【解决方案2】:

    testvar[1] 是该数组索引的值,即数字 2。数字没有长度属性,您正在检查未定义的 2.length。如果你想要数组的长度,只需检查 testvar.length

    【讨论】:

      【解决方案3】:

      整数没有方法长度。试试字符串

      var testvar={};
      testvar[1]="2";
      alert(testvar[1].length);
      

      【讨论】:

        【解决方案4】:

        如果 length 未定义,您可以使用:

        function count(array){
        
            var c = 0;
            for(i in array) // in returns key, not object
                if(array[i] != undefined)
                    c++;
        
            return c;
        }
        
        var total = count(array);
        

        【讨论】:

          【解决方案5】:
                 var mode = [];
                          $("input[name='mode[]']:checked").each(function(i) {
                              mode.push($(this).val());
                          })
           if(mode.length == 0)
                          {
                             alert('Please select mode!')
                          };
          

          【讨论】:

          • "为什么下面会返回'undefined'?"
          【解决方案6】:
          var array=[];
          
          array.push(array);  //insert the array value using push methods.
          
          for (var i = 0; i < array.length; i++) {    
              nameList += "" + array[i] + "";          //display the array value.                                                             
          }
          
          $("id/class").html(array.length);   //find the array length.
          

          【讨论】:

            【解决方案7】:
            obj={};
            
            $.each(obj, function (key, value) {
                console.log(key+ ' : ' + value); //push the object value
            });
            
            for (var i in obj) {
                nameList += "" + obj[i] + "";//display the object value
            }
            
            $("id/class").html($(nameList).length);//display the length of object.
            

            【讨论】:

            • 请不要在没有任何解释的情况下发布代码。无论如何,这段代码似乎与最初询问的内容没有任何关系。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多