gpt4 book ai didi

javascript - 对象中的 getFullYear()

转载 作者:行者123 更新时间:2023-12-03 04:13:47 24 4
gpt4 key购买 nike

谁能解释一下为什么这不起作用:

var todayDate = new Date();
var todayYear = todayDate.getFullYear();

var User = {
firstName: "John",
lastName: "Doe",
email: "email@email.com",
dob: new Date(85, 1, 1),
userBirthYear: dob.getFullYear(),
age: todayYear - userBirthYear,
url: "http://www.google.com",
bio: "I love pizza",
interests: ["food", "NBA", "movies"]
}

userBirthYear似乎没有初始化。如果我移动 userBirthYear在对象之外作为单独的变量,它工作得很好。

最佳答案

dob 不是变量,它是 User 对象的属性。

但是在编译整个对象之前,您无法直接访问对象属性

你可以这样做;

var User = {
firstName: "John",
lastName: "Doe",
email: "email@email.com",
dob: new Date(85, 1, 1),
age: todayYear - userBirthYear,
url: "http://www.google.com",
bio: "I love pizza",
interests: ["food", "NBA", "movies"]
}
// User object now exists, modify it any way you need
User.userBirthYear = User.dob.getFullYear();

关于javascript - 对象中的 getFullYear(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44228132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com