JavaScript 对象的长度?


假设下面是我们 Student 对象 -

var studentObject = new Object();
studentObject["studentFirstName"] = "John";
studentObject["studentLastName"] = "Doe";
studentObject["studentAge"] = 22;
studentObject["studentCountryName"] = "US";
studentObject["studentCollegeName"] = "MIT";
studentObject["studentSubjectName"] = "JavaScript";

让我们求长度。

你可以使用对象中可用的键的概念,如果存在键,则增加计数器变量,并在完成 for 循环后返回计数器。

示例

var studentObject = new Object();
studentObject["studentFirstName"] = "John";
studentObject["studentLastName"] = "Doe";
studentObject["studentAge"] = 22;
studentObject["studentCountryName"] = "US";
studentObject["studentCollegeName"] = "MIT";
studentObject["studentSubjectName"] = "JavaScript";
Object.findLength = function (stObject) {
   var counter = 0, k;
   for (k in stObject) {
      if (stObject.hasOwnProperty(k))
         counter++;
   }
   return counter;
};
var lengthOfStudentObject = Object.findLength(studentObject);
console.log("The length Student Object is=" + lengthOfStudentObject);

要运行上述程序,你需要使用以下命令 -

node fileName.js.

我的文件名是 demo191.js。

输出

将生成以下输出 -

PS C:\Users\Amit\javascript-code> node demo191.js
The length Student Object is=6

更新时间:14-9 月-2020

124 次浏览

开启你的事业

通过完成课程获得认证

开始
广告