为什么我通过 typeof 返回“undefined”,我该如何防止这种情况?

编程入门 行业动态 更新时间:2024-10-03 06:33:50

为什么我通过 typeof 返回“undefined”,我该如何防止<a href=https://www.elefans.com/category/jswz/34/1770516.html style=这种情况?"/>

为什么我通过 typeof 返回“undefined”,我该如何防止这种情况?

以下代码:

"use strict"

 const students = [
  {firstname: "Max", lastname: "Mustermann", age: 21},
  {firstname: "Laura", lastname: "Müller", age: 25},
  {firstname: "Julia", lastname: "Schreiber", age: 30},
  {firstname: "Tobias", lastname: "Lieb", age: 19}
]

console.log( typeof students.age)


退货

undefined
。我不明白为什么。我还在我的代码中添加了一个财产年龄为空的学生,并试图获得如下平均值:

students.push({
  firstname: "Christian",
  lastname:"Schmidt",
  age:null
})

let ageSum = 0

for (const student in students){
 if(typeof student.age){
  ageSum += student.age
 }
}

又来了,我不明白为什么

typeof
返回
undefined
。在处理类型对象属性之前,在 JavaScript 中是否有更好的方法来检查它们?

回答如下:

students
没有
age
属性,因此它是
undefined
。如果你想引用个别学生的
age
(使用下标运算符),你会看到它确实是一个数字:

"use strict"

 const students = [
  {firstname: "Max", lastname: "Mustermann", age: 21},
  {firstname: "Laura", lastname: "Müller", age: 25},
  {firstname: "Julia", lastname: "Schreiber", age: 30},
  {firstname: "Tobias", lastname: "Lieb", age: 19}
]

console.log( typeof students[0].age)
// Here --------------------^

更多推荐

为什么我通过 typeof 返回“undefined”,我该如何防止这种情况?

本文发布于:2024-05-31 04:47:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这种情况   我该   如何防止   typeof   undefined

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!