This question already has answers here:
How to append something to an array?
                            
                                (30个答案)
                            
                    
                在4个月前关闭。
        

    

我正在构建一个bankAccount程序,尝试将我的DD添加到全局变量中,但是当我从构造函数创建新对象然后将它们添加到bankAccount中时,它仅显示最后创建的dd?

我想做的是将所有DD推送到bankAccount ..

代码如下



// Created my bankAccount with the value of 0
var bankAccount = {};

// Object constructor to created direct debit with name and cost
function DirectDebit(name, cost) {
  this.name = name;
  this.cost = cost;
}

// Creating a new DD for my phone
var phone = new DirectDebit("Phone ", 20);
var car = new DirectDebit("Car ", 250);

function addToBank (dd) {
    bankAccount = dd
}

addToBank(phone)
addToBank(car)

console.log(bankAccount);





输出:

DirectDebit { name: 'Car ', cost: 250 }

最佳答案

将bankAccount创建为一个数组,然后将数据推送到该数组中而不是进行设置。

var bankAccount = [];
function addToBank (dd) {
    bankAccount.push(dd);
}

关于javascript - 将javascript对象值添加到全局var中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59563521/

10-12 07:08