Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 744
Mardymar Avatar asked Aug 05 '26 00:08

Mardymar


1 Answers

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;
  // ...
}
like image 52
Andreas Louv Avatar answered Aug 06 '26 15:08

Andreas Louv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!