简体   繁体   English

JavaScript多维数组长度问题

[英]Javascript multidimensional array length problem

JavaScript multidimensional array length always returning 0, how can I solve this problem? JavaScript多维数组长度始终返回0,如何解决此问题?

在此处输入图片说明

 class test { static init() { test.arr = []; } static add() { let user_id = Math.floor(Math.random() * 10000); if (test.arr["u_" + user_id] === undefined) { test.arr["u_" + user_id] = []; } test.arr["u_" + user_id].push({ "somedata": "here" }); } static length() { return test.arr.length; } } test.init(); test.add(); test.add(); console.log(test.arr.length); //Always returning 0 

An array is a sorted set of numeric key value pairs. 数组是一组数字键值对的排序集合。 "_u" + user_id is not numeric, it's a string, therefore it gets stored as a regular property on the array (it behaves like an object) and not as part of the array itself. "_u" + user_id不是数字,它是一个字符串,因此它作为常规属性存储在数组中(其行为类似于对象),而不是数组本身的一部分。 If you want to use a key-value storage with a length, use a Map . 如果要使用具有一定长度的键值存储,请使用Map

 const test = { // no need for a class if you dont have instances
   arr: new Map(), // no need for that unneccessary init
   add() {
    let user_id = Math.floor(Math.random() * 10000);
    if(!this.arr.has("u_" + user_id)) { // I prefer "this" over "test", both work however
      this.arr.set("u_" + user_id, []);
    }
    this.arr.get("u_" + user_id).push({"somedata": "here"});
   },

   length() {
    return this.arr.size; //Note: it is "size" not "length" on a Map
   },
};

Sidenote: arr and test are very bad names. 旁注: arrtest是非常不好的名字。

An array index can be defined as number only. 数组索引只能定义为数字。 If you want to get the length of an array, there are two ways to achieve this. 如果要获取数组的长度,有两种方法可以实现。

  • You need to define the index as number instead of a string. 您需要将索引定义为数字而不是字符串。
  • Make a separate object, add your object ( {"somedata": "here"} ) into the object and push it into the array. 制作一个单独的对象,将您的对象( {"somedata": "here"} )添加到该对象中,然后将其推入数组。 Check the code below. 检查下面的代码。

     let test=[] let obj = {} let user_id = Math.floor(Math.random() * 10000); if(obj["u_" + user_id] === undefined) { obj["u_" + user_id] = []; } obj["u_" + user_id] = {"somedata": "here"}; test.push(obj) 

Hope this will be helpful. 希望这会有所帮助。

Check out the following jsbin I made you. 查看以下我为您制作的jsbin。 https://jsbin.com/xeqacuf/edit?console https://jsbin.com/xeqacuf/edit?console

    constructor()
    {
        console.log("new object created");
        this.test = { arr : {} };
    }

It's close to what you are trying to do... Let me know if you need explanation or more help. 它接近您要尝试的操作。如果您需要解释或更多帮助,请告诉我。 I'm willing to assist as much as youd like. 我愿意竭尽所能。 Notice that I changed the datatype from collection to objectKeyValue which allows you to query the object by key like you wanted. 请注意,我已将数据类型从collection更改为objectKeyValue,这使您可以根据需要按键查询对象。

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

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