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

问题描述 投票:0回答:2

以下代码:

"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 中是否有更好的方法来检查它们?

javascript node.js typeof
2个回答
1
投票

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
投票

有点混乱你的代码。我更喜欢在像你一样迭代 javascript 数组时使用索引器。

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(`Age of first student is ${students[0].age} and it's of type ${typeof students[0].age}`)

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

        let ageSum = 0

        for (var i = 0; i < students.length; i++){
            console.log(students[i])
            if(typeof students[i].age === "number"){
                ageSum += students[i].age
            }
        }

        console.log(`Total age of students is ${ageSum}`)
© www.soinside.com 2019 - 2024. All rights reserved.