gpt4 book ai didi

Javascript 对象构造函数和 boolean 变量

转载 作者:行者123 更新时间:2023-11-28 20:41:39 24 4
gpt4 key购买 nike

我正在尝试创建一个 JS 对象构造函数,但想使用 boolean 运算声明该对象的属性之一。不知怎的,我弄错了 - 请指教!

谢谢!交流

function Student(gender, name, id, age, likes) {
this.gender = gender;
this.name = name;
this.id = id;
this.age = Boolean () {
var age = x;
if (age >= 21) {
return "adult";
} else {
return "minor";
}
};
this.likes = likes;
}

window.onload = init;

function init() {
var jessica = new Student("female", "Jessica", 12, 21, ["butterflies", "flowers", "music"]);
var jessicaJSON = JSON.stringify(jessica);
console.log(jessicaJSON);

var anotherJessica = JSON.parse(jessicaJSON);
console.log(anotherJessica);

}

最佳答案

这是为您固定的学生功能。使用三元 if 语句而不是“Boolean() {}”,这实际上不是有效的 Javascript 代码 + boolean 值要么是 true 要么是 false,您返回了“adult”或“minor”,它们是字符串,并且与无论如何, boolean 类型。

function Student(gender, name, id, age, likes) {
this.gender = gender;
this.name = name;
this.id = id;
this.likes = likes;
this.age = (age >= 21 ? "adult" : "minor");
}

关于Javascript 对象构造函数和 boolean 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14291998/

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