简体   繁体   中英

What is the JavaScript equivalent of this Swift code?

I learnt that you could have arrays within classes in Swift this way (quiz question example):

// 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"))
    }
}

Then, to output:

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
}

I would like to know if there is an equivalent to this in JavaScript.

I am trying to develop a time zone converter. Here is the JavaScript code I'm trying:

// JavaScript

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

class Cities {
    // ???
}

I am try to give Cities an array containing several of City . As you can see, Swift has an easy way to do it. Is there something similar I can do in JavaScript?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM