2017-04-18 89 views
0

我完全被我遇到的錯誤困惑。我一直在努力尋找解決辦法,我想知道有沒有人看到過這樣的事情,或知道發生了什麼。JavaScript Array元素消失

基本上發生的是我有2個數組,填充了對象。我想看看它們,並檢查第二個數組的所有元素(compareArrays()函數中的比較)是否存在於第一個數組(myArray)中。如果比較數組中有同一對象的多個實例,則第一個應該有相同的數字。

我正在使用Angular with Typescript。這裏是我的代碼:

/* 
* I get todaysItems a little higher in the constructor from a different service. It looks 
* like this: 
*  { 
*   day: "Monday", 
*   price: 5.00, 
*   items_name: "1/4 Pounder with Cheese and Chips", 
*   items: [ 
*    {name: "1/4 Pounder with Cheese", price: 4.50}, 
*    {name: "Small Chips", price: 2.50} 
*   ], 
*   ad_hoc_price: 7 
*  } 
*/ 
private todaysItems: Item[] = []; 

compareArrays (myArray: Item[], compare: Item[]) { 
    var self = this; 
    if (compare.every(function(val) { 
     var index = self.arrayObjectIndexOf(myArray, val.name, "name"); 
     if (index !== -1) { 
      myArray.splice(index, 1); 
      return true; 
     } else { 
      return false; 
     } 
    })) { 
     return true; 
    } else { 
     return false; 
    } 
} 

arrayObjectIndexOf(myArray, searchTerm, property) { 
    for(var i = 0, len = myArray.length; i < len; i++) { 
     if (myArray[i][property] === searchTerm) { 
      return i; 
     } 
    } 
    return -1; 
} 

/* 
* The cart has a property items_in_cart which is working fine, I can add elements to it 
* and remove them with no issue. 
*/ 

addItem (item: Item, totalPrice: number, cart: Cart) { 
    totalPrice += item.price; 
    cart.items_in_cart.push(item); 
    return { 
     newPrice: totalPrice, 
     newCart: cart 
    } 
} 

好的,所以addItem()函數工作正常,就像預期的一樣。但離奇的是,當我改變它,所以它看起來像

addItem (item: Item, totalPrice: number, cart: Cart) { 
    totalPrice += item.price; 
    cart.items_in_cart.push(item); 
    console.log(this.compareArrays(cart.items_in_cart, this.todaysItems)); 
    return { 
     newPrice: totalPrice, 
     newCart: cart 
    } 
} 

只是補充說一點的console.log(),它調用我的compareArrays()函數踢所有this.todaysItems的元素出來的車。 items_in_cart。這是超級怪誕的,我不知道發生了什麼。

任何想法?

+0

多次閱讀帖子。沒有得到上下文。修改它 – Aravind

+0

我剛剛在頂部添加了一點解釋,這是否使它更清晰? – Will

+0

你有一個比較邪惡的'compareArrays'函數。這就是爲什麼。具體來說,它不會做它所宣稱的。這就像「如果我們找到一場比賽,那麼我們就開始銷燬東西!」。如果一個函數不能將其命名爲'compareArrays'。 –

回答

2

只是加入那個小的console.log()它調用我compareArrays()函數踢所有元素

compareArrays的功能例如變異其數組參數的

compareArrays (myArray: Item[], compare: Item[]) { 
    var self = this; 
    if (compare.every(function(val) { 
     var index = self.arrayObjectIndexOf(myArray, val.name, "name"); 
     if (index !== -1) { 
      myArray.splice(index, 1); // HERE 

由於compareArrays是不是你可以期望陣列通過調用它可以改變一個純函數。

+1

我會如何避免這種情況?我改變它添加var tempArray = myArray;然後做了拼接,但我得到了相同的行爲。 – Will

+1

克隆數組的正確方法:'var tempArray = myArray.slice()' – basarat

+0

這很有效,謝謝! – Will