简体   繁体   English

如何在Javascript中使用两个空对象初始化数组

[英]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 : 您需要使用关键字new来制作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 : 您还可以通过使用instanceof进行检查来满足new关键字的需求:

// 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('','')]

资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM