關於 JS 陣列,物件 length 使用的坑

小彭友發表於2020-05-25

場景: laravel中前端請求後端返回一個陣列,返回格式如下:

 $data = [ "datalist" =>
        [   16 => ["name" => "鋼筋工",
              "count" => 55,
              "num" => 16 ],
            46 => [ "name" => "木工二班",
              "count" => 57,
              "num" => 46 ],
            25 =>[ "name" => "塔吊",
              "count" => 6,
              "num" => 25 ],
            31 => [ "name" => "機電",
              "count" => 5,
              "num" => 31 ],
        ],
        "other" => 0,
        "count" => 188 ,
    ];

JS中拿到資料是個物件,前端獲取物件長度使用了(假如返回值用res接收)

var len = res.datalist.length

結果len的值是undefined.

解決:
方案1:

$data = [ "datalist" =>
        [   0 => ["name" => "鋼筋工",
              "count" => 55,
              "num" => 16 ],
            1 => [ "name" => "木工二班",
              "count" => 57,
              "num" => 46 ],
            2 =>[ "name" => "塔吊",
              "count" => 6,
              "num" => 25 ],
            3 => [ "name" => "機電",
              "count" => 5,
              "num" => 31 ],
        ],
        "other" => 0,
        "count" => 188 ,
    ];

將datalist變成從0開始的索引陣列就好了(用了函式array_values()從新排序了),這樣計算出來的長度len = 4;
方案2

var arr = Object.keys(res.datalist);
var len = arr.length; //4

這樣的結果len也是4;

總結: 因為方便寫後續的程式碼,我選擇了方案1 ,感覺JS的陣列(從0按順序排序)和物件(key值也是0,1,2排序)就是一樣一樣的。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章