Using indexOf to filter an array

前端 未结 2 774
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 11:15

I am trying to output the first two objects in the events array using indexOf.

This doesn\'t return anything:

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

var          


        
相关标签:
2条回答
  • 2021-01-12 11:35

    You are doing it wrong, it should go like this.

    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)

    0 讨论(0)
  • 2021-01-12 11:50

    With ES6, you could use Set for faster access with larger data sets.

    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);

    0 讨论(0)
提交回复
热议问题