我只是想知道为什么我的第二次插入会覆盖我的第一个对象值。
const customer = {
name: '',
totalCups: 0
}
$('#btnAdd').click(function() {
debugger
var itemName = $('#customerName');
var itemTotalCups = $('#customerTotalCups');
// Basic Validation
if (itemName.val().trim() === "") {
return;
}
if (parseInt(itemTotalCups.val()) === 0) {
return;
}
customer.name = itemName.val();
customer.totalCups = itemTotalCups.val();
// Data structure Queue
order.unshift(customer);
console.log(order);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<input id="customerName" type="text" class="form-control" placeholder="Enter customer's name" />
<input id="customerTotalCups" type="number" class="form-control" placeholder="Enter number of cups" min="1" />
<span class="input-group-btn">
<button id="btnAdd" class="btn btn-default" type="submit">
<i class="fa fa-plus"></i>
</button>
</span>
</div>
<button id="btnAdd">Add</button>
<div id="CurentOrder"></div>
例如我得到的第一个插入内容
0: {name: "Alan", totalCups: "1"}
当我对另一个数据第二次插入执行.unshift时,它变为以下内容:
0: {name: "Alan", totalCups: "1"}
1: {name: "Alan", totalCups: "1"}
答案 0 :(得分:2)
尝试并运行以下代码,以查看客户对象和订单数组的情况,特别是在第二次调用时。应该弄清楚问题出在什么:)
const customer = {
name: '',
totalCups: 0
}
let i = 0;
let order = [];
function add () {
customer.name = i++
customer.totalCups = Math.random ()
// Data structure Queue
order.unshift(customer);
console.log(order);
}
add ();
add ();
console.log (order)
console.log (order [0] === order [1])
答案 1 :(得分:1)
调用函数时,每次函数更改“全局”对象customer
时,您都尝试将客户的副本放入order
数组中。因此,在客户属性更改后,其所有副本也将更改。为了避免这种行为,您需要使用Object.assign()
方法来填充order
:
order.unshift(Object.assign({}, customer));
const customer = {
name: '',
totalCups: 0
}
$('#btnAdd').on('click', function() {
var itemName = $('#customerName').val().trim();
var itemTotalCups = $('#customerTotalCups').val();
// Basic Validation
if ( (itemName === "") || (parseInt(itemTotalCups) === 0) ) return;
customer.name = itemName;
customer.totalCups = itemTotalCups;
// Data structure Queue
order.unshift(Object.assign({}, customer));
console.log(order);
})
var order = [];
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<input id="customerName" type="text" class="form-control" placeholder="Enter customer's name" />
<input id="customerTotalCups" type="number" class="form-control" placeholder="Enter number of cups" min="1" />
<span class="input-group-btn">
<button id="btnAdd" class="btn btn-default" type="submit">
<i class="fa fa-plus"></i>
</button>
</span>
</div>
<button id="btnAdd">Add</button>
<div id="CurentOrder"></div>
更多说明-您使用相同的id="btnAdd"
创建了两个html元素,但是id
应该是唯一的标识符。