过滤数组并保持对原始数组的索引的引用?

时间:2017-06-22 18:13:55

标签: javascript

我试图过滤不正确答案的答案数组,然后只从原始数组中删除其中的两个。

代码:

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数组中选择两个随机答案,并从答案数组中获取索引。

2 个答案:

答案 0 :(得分: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);




答案 1 :(得分:1)

要选择正确答案以及两个随机错误答案,您可以使用以下代码。这将使原始数组保持原样,并返回对原始数组中对象的引用。



    <Router history={history}>
        <Switch>
            <Route exact path="/" component={App}>
                <Route path="/cards" component={Example} />
            </Route>
        </Switch>
    </Router>
&#13;
&#13;
&#13;