Mardymar
Mardymar

Reputation: 419

How to initialize an array with two empty objects in Javascript

I am making an angular controller and need to initialize an array with two empty objects so that two lines will appear on the screen and I need to initialize a new object in the array when a + button is clicked. I am unsure about how to go about doing this.

This is my best attempt:

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope', '$q', function($scope, $q) {

    $scope.arr = [card('',''),card('','')];
    $scope.addLine = function(index){
        $scope.arr.push(card('',''));
    }
    $scope.removeLine = function(index){
        $scope.arr.splice(index, 1);
    }
}]);

function card(term, definition){
    this.term = term;
    this.definition = definition;
}

Upvotes: 3

Views: 274

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

You need to use the keyword new to make an instance of card:

$scope.arr = [new card('',''), new card('','')];
//            ^                ^ See new keyword  
$scope.addLine = function(index){
    $scope.arr.push(new card('',''));
    //              ^ See new keyword
}

Also you should consider always Capitalize your constructors (This way you can indicate that its an constructor:

new Card('', '');
function Card(...) {...}

You can also boil the need of the new keyword away by checking with instanceof:

// No need for new anymore:
var card = Card(1, 2, 3); 
console.log(card instanceof Card); // true
function Card(a, b, c) {
  if (!(this instanceof Card)) return new Card(a, b, c);
  this.a = a;
  this.b = b;
  // ...
}

Upvotes: 2

djechlin
djechlin

Reputation: 60748

[new card('',''), new card('','')]

source

Upvotes: 0

Related Questions