在下面的代码中;为什么“self.ticketCollection.indexOf(t)”中的“self.Addticket-function always -1 ???
在page_load之后,我按下New(newTicket),然后按ADD(addTicket)。这工作正常,并且(“ny”,“ - 1”)的记录被添加到我的ticketCollection中。然后当我重复这个时,另外一个记录完全相同。调试器(FireBug)告诉我“self.ticketCollection.indexOf(t)”在两种情况下均为-1。为什么呢?
function Ticket(ticketname, cost) {
var self = this;
//alert("ikke implementer fullt ut ennå!");
self.ticketname = ko.observable(ticketname);
self.cost= ko.observable(cost);
} // end Ticket
//==============================================================
function ViewModel() {
var self = this;
//------ initiate ----------------------------------------------
// the product we want to view/edit
self.selectedTicket = ko.observable();
self.ticketCollection = ko.observableArray(
[
new Ticket("Bus", "$2"),
new Ticket("Ferry", "$3"),
new Ticket("Bicycle", "$1")
]);
// selected item from ticket list-view
self.listViewSelectedItem = ko.observable();
// push any changes in the list view to our main selectedTicket
self.listViewSelectedItem.subscribe(function (ticket) {
if (ticket) {
self.selectedTicket(ticket);
}
}); // self.listViewSelectedItem.subscribe //
//---- NEW button pressed --------------------------------------
self.newTicket = function () {
// create a new instance of a Ticket
var t = new Ticket("ny", "-1");
// set the selected Ticket to out new instance
self.selectedTicket(t);
}.bind(this);
//---- ADD to collection -----------------------------------------
self.addTicket = function () {
//alert("ADD is pushed!");
// get a reference to out currently selected product
var t = self.selectedTicket();
// ignore if null
if (!t) { return; }
// check to see that the ticket doesn\t already exist
if (self.ticketCollection.indexOf(t) > -1) {
return;
}
// add the product to the collection
self.ticketCollection.push(t);
// clear out the selected product
self.selectedTicket(t);
//self.listViewSelectedItem(t)
};
} // end ViewModel
提前完成!
阿斯勒:)
答案 0 :(得分:4)
仅仅因为你有两个包含完全相同值的Ticket
个对象,并不意味着这两个对象是相等的。这就是indexOf
每次返回-1的原因 - 因为ticketCollection
可观察数组不包含您要检查的确切项目。这个SO问题很好地解释了JavaScript对象的平等性:How to determine equality for two JavaScript objects?
您应该检查indexOf
中的任何项目是否与新ticketCollection
和ticketName
匹配,而不是使用数组上的cost
。 ,来袭票。
我将添加一个我的意思的例子:
for(var i=0, len=self.ticketCollection().length; i < len; i++){
if ((t.ticketname() === ticketCollection()[i].ticketname()) && (t.cost() === ticketCollection()[i].cost())) {
alert('Found the object in the observable array')
}