Chang Yao Liu
Chang Yao Liu

Reputation: 49

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?

Upvotes: 0

Views: 279

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85102

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

Upvotes: 3

Related Questions