这种情况?"/>
为什么我通过 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”,我该如何防止这种情况?
发布评论