2016-01-20 77 views
1

我想知道是否有一種簡單的方法來從數組中選擇一個隨機對象,其中一個對象屬性與變量匹配。從具有特定參數的數組中檢索對象

事情是這樣的:

var ninjas = [ 
    { name: "Sanji Wu", affiliation: "good" }, 
    { name: "Chian Xi", affiliation: "good" }, 
    { name: "Chansi Xian", affiliation: "bad" }, 
    { name: "Chin Chu", affiliation: "bad" }, 
    { name: "Shinobi San", affiliation: "neutral" }, 
    { name: "Guisan Hui", affiliation: "neutral" } 
]; 

function getRandom(attr) { 
    var r = Math.floor(Math.random() * ninjas.length); 

    //pseudo code below 
    if (this affiliation is "attr") { 
     return a random one that matches 
    } 
    // end pseudo code 
}; 

var randomItem = getRandom("good"); 

回答

4

相當直接的創造,只有匹配的元素的數組,然後抓住隨機從一個條目:

function getRandom(desiredAffiliation) { 
    var filtered = ninjas.filter(function(ninja) { 
     return ninja.affiliation == desiredAffiliation; 
    }); 
    var r = Math.floor(Math.random() * filtered.length); 
    return filtered[r]; 
} 

如果你想你尋找一個運行時的東西的財產,你也可以這樣做,使用括號符號:

function getRandom(propName, desiredValue) { 
    var filtered = ninjas.filter(function(ninja) { 
     return ninja[propName] == desiredValue; 
    }); 
    var r = Math.floor(Math.random() * filtered.length); 
    return filtered[r]; 
} 

你可能會想調整那些以允許沒有匹配條目的可能性。現在他們會在這種情況下返回undefined,因爲他們會嘗試返回數組的第0個條目,而這個數組中沒有任何內容,這不是錯誤,但會導致值爲undefined

相關問題