javascript-objects - JavaScript object - JavaScript对象的长度

Js object add property / javascript

我有一个JavaScript对象。有没有一种内置的或公认的最佳实践方法来获取这个对象的长度?

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

Peter Mortensen



Answer #1
<script>
myObj = {"key1" : "Hello", "key2" : "Goodbye"};
var size = Object.keys(myObj).length;
console.log(size);
</script>

<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>

这对我很有用

var size = Object.keys(myObj).length;