这个Swift代码的JavaScript等效代码是什么?

时间:2019-07-24 12:59:03

标签: javascript swift

我了解到您可以在Swift中的类中使用数组(测验问题示例):

// Swift

class Question {
    var ques:String
    var ans:Bool
    var expl:String
    init(quesTitle:String, answer:Bool, explanation:String) {
        self.ques = quesTitle
        self.ans = answer
        self.expl = explanation
    }
}

class AllQues {
    var questions:[Question] = []
    init() {
        questions.append(Question(quesTitle: "Is xxx true?", answer: false, explanation: "Explanation here."))
        questions.append(Question(quesTitle: "This has to be true", answer: false, explanation: "But it isn't"))
    }
}

然后,输出:

var allQuestions = AllQues()
func loadQuestion() {
    questionLabel.text = "Question \(number + 1) of \(allQuestions.questions.count)\n\n \(allQuestions.questions[number].ques)"
    correctAnswer = allQuestions.questions[number].ans
    explanation = allQuestions.questions[number].expl
}

我想知道JavaScript中是否与此等效。

我正在尝试开发时区转换器。这是我正在尝试的JavaScript代码:

// JavaScript

class City {
    constructor(city, country, offset) {
        this.city = city;
        this.country = country;
        this.offset = offset;
    }
}

class Cities {
    // ???
}

我试图给Cities一个包含多个City的数组。如您所见,Swift有一个简单的方法。我可以用JavaScript做类似的事情吗?

1 个答案:

答案 0 :(得分:3)

class Cities {
  constructor() {
    this.cities = [];
    this.cities.push(new City("foo", "bar", "baz"));
    this.cities.push(new City("snap", "crackle", "pop"));
  }
}