2016-10-10 6 views
3

私は、eventOfを使用してイベント配列の最初の2つのオブジェクトを出力しようとしています。indexOfを使用して配列をフィルタリングする

これは何も返しません:私はこのような機能を変更

var whiteList=['css','js']; 

var events =[ 
    {file: 'css/style.css', type:'css'}, 
    {file: 'js/app.js', type:'js'}, 
    {file: 'index/html.html', type:'html'} 
]; 

var fileList= events 
    .filter(function(event){ 
    return event.type.indexOf(whiteList) >- 1 
    }) 

console.log(fileList); 

場合、私はそれがHTMLオブジェクトを返すことが期待されるものの、それは、CSSやJSオブジェクトを返します。

var fileList= events 
    .filter(function(event){ 
    return event.type.indexOf('html') 
    }) 
+1

'event.type.indexOf( 'HTML')' 0を返す( 'H' の位置) - '0'は 'false'として解釈されます。 –

+0

'whatever.indexOf([1,2,3])'から何を期待しますか? – Redu

答えて

9

あなたは間違っている、これはこのようになるはずです。 ES6で

var whiteList = ['css', 'js']; 
 

 
var events = [{ 
 
    file: 'css/style.css', 
 
    type: 'css' 
 
}, { 
 
    file: 'js/app.js', 
 
    type: 'js' 
 
}, { 
 
    file: 'index/html.html', 
 
    type: 'html' 
 
}]; 
 

 
var fileList = events.filter(function(event) { 
 
    return whiteList.indexOf(event.type) > -1 
 
}) 
 

 
console.log(fileList)

+1

これは完璧で、私が書いていた別のコードにも使えました。ありがとう! – Chef1075

4

、あなたは大規模なデータセットと高速アクセスのためSetを使用することができます。

var whiteList = ['css', 'js'], 
 
    whiteSet = new Set(whiteList), 
 
    events = [{ file: 'css/style.css', type: 'css' }, { file: 'js/app.js', type: 'js' }, { file: 'index/html.html', type: 'html' }], 
 
    fileList = events.filter(event => whiteSet.has(event.type)); 
 

 
console.log(fileList);

関連する問題