2017-06-22 72 views
-1

我試圖過濾不正確答案的答案數組,然後只從原始數組中刪除其中的兩個。過濾數組並保留對原始數組索引的引用?

代碼:

var answers = [ 
    {text: "foo", isCorrect: false}, 
    {text: "bar", isCorrect: true}, 
    {text: "foo2", isCorrect: false}, 
    {text: "bar2", isCorrect: false} 
] 
var inCorrect = answers.filter((v, i) => !v.isCorrect); 

選擇從inCorrect陣列兩個隨機答案,並得到了答案,數組的索引。

+0

'i'是在'filter'回調的指數。 –

+1

您的數據如何被綁定到您的視圖?什麼決定了答案是否被「禁用」?答案是否有一個「主動」或「禁用」屬性或UI正在查看的內容? – mhodges

+0

@mhodges是的即時通訊作爲道具傳遞給孩子組件<答案isSelected = {假} isCorrect = {假} ... />等 –

回答

1

要選擇有兩個隨機不正確的答案沿着正確的答案,你可以使用下面的代碼。這會使原始數組保持不變,並返回對原始數組中對象的引用。

var answers = [ 
 
    {answer: "foo", isCorrect: false}, 
 
    {answer: "bar", isCorrect: true}, 
 
    {answer: "foo2", isCorrect: false}, 
 
    {answer: "bar2", isCorrect: false} 
 
] 
 
function getRandom (ceiling) { 
 
    return Math.floor(Math.random() * (ceiling || 1)); 
 
} 
 
function fiftyFifty (answers) { 
 
    var correct = answers.find(answer => answer.isCorrect); 
 
    var incorrectAnswers = answers.filter(answer => !answer.isCorrect); 
 
    // grab n answers unless there are less than n incorrect answers to choose from 
 
    var numberOfIncorrects = Math.min(2, incorrectAnswers.length); 
 
    var incorrectsToUse = []; 
 
    for (var i = 0; i < numberOfIncorrects; i++) { 
 
     let randomIndex = getRandom(incorrectAnswers.length); 
 
     // splice elem out of array so it doesn't get randomly selected twice 
 
     incorrectsToUse.push(incorrectAnswers.splice(randomIndex, 1)[0]); 
 
    } 
 
    return [correct].concat(incorrectsToUse); 
 
} 
 

 
console.log(fiftyFifty(answers)); 
 
console.log(fiftyFifty(answers)); 
 
console.log(fiftyFifty(answers));

+0

謝謝@mhodges,關閉!我需要得到兩個不正確的答案。而不是一個正確的和一個不正確的。 :) –

+0

@BrainYoung哦,gotcha。輕鬆修復。待機 – mhodges

+0

@BrainYoung更新。但不知道你想如何輸出。你想讓它們在單個數組中嗎?還是你想讓它們放在一個帶有{correct:obj,incorrect:[obj,obj]}的對象中?還是你想讓不正確的答案嵌套在它們自己的數組中?'[correct, [不正確,錯誤2]]'? – mhodges

1

是不是隻分配回answers工作?

var answers = [ 
 
    {val : "foo", isCorrect: false}, 
 
    {val : "bar", isCorrect: true}, 
 
    {val : "foo2", isCorrect: false}, 
 
    {val : "bar2", isCorrect: false} 
 
]; 
 
answers = answers.filter(v => v.isCorrect); 
 

 
console.log(answers);

+0

沒有,改變answers數組會改變狀態! –

+0

@BrainYoung我很困惑..你想保持對答案的參考,從'answers'中刪除不正確的答案,而不修改'answers'數組? – mhodges

+0

我想要一個新的數組不正確的答案(3答案),然後從這些3中選擇2個隨機元素。這2個答案將淡出在用戶界面,所以答案不能改變。 –