简体   繁体   中英

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;
}

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;
  // ...
}
[new card('',''), new card('','')]

资源

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