最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin30浏览0评论

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

为什么我通过 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 --------------------^
发布评论

评论列表(0)

  1. 暂无评论