2016-03-21 165 views
-4
var arr = ["Chandelier", "Big Girls Cry", "Burn the Pages", "Eye of the Needle", "Hostage", "Straight for the Knife", "Fair Game", "Elastic Heart", "Free the Animal", "Fire Meet Gasoline", "Cellophane", "Dressed In Black", "Chandelier", "Elastic Heart", "Chandelier", "Chandelier", "Elastic Heart", "Elastic Heart", "Big Girls Cry", "Big Girls Cry"]; 

$.each(arr, function(i,obj){ 
console.log(obj); 
}); 

如何確保我的數組是唯一的?刪除重複數組項目

+2

哇,張貼 –

+0

@WesFoster我在這種情況下使用$。每前搜索。 –

+0

那麼你是否要求使用'$ .each'去除重複的方法?很顯然,@WesFoster是 –

回答

1

Array#filter()和一個臨時對象。

var arr = ["Chandelier", "Big Girls Cry", "Burn the Pages", "Eye of the Needle", "Hostage", "Straight for the Knife", "Fair Game", "Elastic Heart", "Free the Animal", "Fire Meet Gasoline", "Cellophane", "Dressed In Black", "Chandelier", "Elastic Heart", "Chandelier", "Chandelier", "Elastic Heart", "Elastic Heart", "Big Girls Cry", "Big Girls Cry"], 
 
    unique = arr.filter(function (a) { 
 
     if (!this[a]) { 
 
      this[a] = true; 
 
      return true; 
 
     } 
 
    }, {});  
 
    
 
document.write('<pre>' + JSON.stringify(unique, 0, 4) + '</pre>');

+0

我使用$ .each來獲取每個名字並將它推到某個地方,這對我的情況有什麼幫助? –

+2

你爲什麼需要$ .each? –

+0

@downvoter,爲什麼? –