Javascript - 使用数组属性定义对象

Javascript - Defining a Object with Array Properties

本文关键字:属性 定义 对象 数组 Javascript      更新时间:2023-09-26

我不知道如何解释我的问题。我想这就是为什么我没有得到好的谷歌搜索结果。无论如何,我想创建一个具有数组属性的对象。 我也尝试了"this.wrong = null;",当我在控制台中运行时得到了"未定义"。

谁能指出我正确的方向?

function Questions(question, answer, wrong) {
this.question = question;
this.answer = answer;
this.wrong = [];
};
var Question5 = new Questions("What is 1+6?", "7", ["4", "45"]);

我的控制台:

4: Questions
   answer: "2"
   question: "What is 1+6?"
   wrong: Array[0]
   __proto__: Questionslength: 5

(编辑添加:我正在制作一个测验应用程序,并试图存储错误的答案选择。

您忘记将数组分配给 wrong 属性:

function Questions(question, answer, wrong) {
    this.question = question;
    this.answer = answer;
    this.wrong = wrong; // <=== Change is here
};

现在,您可以按照当前的方式创建对象,wrong 属性将包含传递给构造函数的数组。