假设以下是我们的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