Franklinc
Franklinc

Reputation: 423

Creating three objects with three properties each

Need help with this JavaScript question:

Now create three new objects. Each object should have the following properties:

  • type: a string specifying what type of mysticalAnimal this is. Unicorns and dinosaurs and yeti and Loch Ness Monsters and polar bears and red pandas are all viable options!
  • collects: an array with a few things this animal might collect
  • canFly: a boolean (true or false — no strings around it, these are reserved keywords) representing whether this animal can fly or not.

Our small paired programming group tried:

var myArray = [];
myArray.push(myObject);
var chipotle = ['unicorn', 'food', true];

How would we properly address this? What is the correct code?

Upvotes: 0

Views: 1485

Answers (2)

Paul
Paul

Reputation: 27433

Here is an example.

An object looks like this:

var Rudolph = {
   type: 'magic reindeer',
   collects: ['insults','sleigh','toys'],
   canFly: true
 }

The above code creates an Object. Objects are very general, the keys are effectively strings and the values can be a string, a number, or even an arrays or another object.

If you are studying custom classes in Javascript, there might be a constructor function that you are supposed to write, or use.

If you had, or are given, a function

function mysticalAnimal(type, collects, canFly){
    this.type = type;
    this.collects = collects;
    this.canFly = canFly;
}

then you could use

var Rudolph = new mysticalAnimal('magic reindeer', 
                                 ['insults','sleigh','toys'],
                                 true);

to create an object that is an instance of mysticalAnimal.

One advantage of this is that the custom function-based object's origin can be tested with:

Rudolph instanceof mysticalAnimal
---> true

Upvotes: 2

iplus26
iplus26

Reputation: 2637

See Object - MDN

You may create one like this:

var obj = {
  type: 'Unicorns',
  collects: ['stuff1', 'stuff2'],
  canFly: true
}

Upvotes: 0

Related Questions