javascript 如何在javascript中找到地图的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54518951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:24:19  来源:igfitidea点击:

How to find the size of map in javascript

javascript

提问by Ratnesh

I want to print the size of map in javascript. I used the command map.sizebut the answer is coming 0 which is not correct.

我想在 javascript 中打印地图的大小。我使用了命令,map.size但答案是 0,这是不正确的。

Here is my source code:

这是我的源代码:

<div id="demo" ></div>
<script>
    function add(test, key, value) {
        if (!test[key]) 
            test[key] = [value];
        else 
            test[key].push(value);
    }
    var mapp = new Map();
    var i,j,k=0;
    for (i=0;i<5;i++)
    {
      for (j=0;j<i;j++)
      add(mapp,i,j);
    }
    document.getElementById('demo').innerHTML="Map size are: "+ mapp.size;
</script>

Output: Map size are: 0

输出: Map size are: 0

However, when I am printing the map entries:

但是,当我打印地图条目时:

for (var m in mapp)
{
        for (k=0;k<mapp[m].length;k++)
        document.write(mapp[m][k]+"  ");

      document.write("<br>");
}

I can see the output:

我可以看到输出:

0 
0 1 
0 1 2 
0 1 2 3 

Please tell me how to find the size of map and why the above code mapp.sizeis not working.

请告诉我如何找到地图的大小以及为什么上面的代码mapp.size不起作用。

回答by zero298

You are treating Maplike an array and using []to access key/value items of it. You need to use the actual methods of Map. Instead of [], use .get()and .set().

Map像对待数组一样对待并使用它[]来访问它的键/值项。您需要使用 的实际方法Map。而不是[],使用.get().set()

Right now, you are setting the actual propertiesof the Mapwhich are not the same as the actual tracked iterable k/v items stored by the data structure.

现在,您正在设置 的实际属性Map这些属性与数据结构存储的实际跟踪可迭代 k/v 项不同。

// Incorrect
const m1 = new Map();

m1["foo"] = "bar";

console.log(m1.length); // undefined
console.log(m1.size); // 0

// Correct
const m2 = new Map();

m2.set("foo", "bar");

console.log(m2.length); // undefined
console.log(m2.size); // 1

回答by Prasann

You are treating Maplike an Array. You should use getand setmethods on map to use the inbuilt functions and not in the array fashion [ ]. Javascript cannot calculate the size of the map if you are not using it correctly

Map就像一个Array. 您应该在地图上使用getset方法来使用内置函数而不是数组方式 []。如果您没有正确使用它,Javascript 将无法计算地图的大小

If you can't change the code, then you can have your own function to calculate the size

如果你不能改变代码,那么你可以有自己的函数来计算大小

function getMapSize(x) {
    var len = 0;
    for (var count in x) {
            len++;
    }

    return len;
}

alert(getMapSize(mapp));

回答by forrestg

Comment to poster's code, the right call should look like samples in this tutorial: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

评论海报的代码,正确的调用应该类似于本教程中的示例:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Depends on data structure, for array like object, we can get map size by:

取决于数据结构,对于像对象这样的数组,我们可以通过以下方式获得地图大小:

Object.getOwnPropertyNames(responseJson.result.priceMap).length;
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).length); 
// logs 3

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

回答by Jagannath Rao

Refer How to check if a Map or Set is empty?.

请参阅如何检查 Map 或 Set 是否为空?.

It works with empty map as well as map with values.

它适用于空地图以及带值的地图。

var list = {}; console.log(Object.keys(list).length );

变量列表 = {}; console.log(Object.keys(list).length);

result = 0

结果 = 0

list = {"key":"hello"}; console.log(Object.keys(list).length );

list = {"key":"你好"}; console.log(Object.keys(list).length);