使用indexOf过滤数组 [英] Using indexOf to filter an array
本文介绍了使用indexOf过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用indexOf输出events数组中的前两个对象。
I am trying to output the first two objects in the events array using 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);
如果我改变这样的函数,它会返回css和js对象,虽然我预计它会返回html对象。
If I change the function like this, it returns the css and js object, although I expected it to return the html object.
var fileList= events
.filter(function(event){
return event.type.indexOf('html')
})
推荐答案
你做错了,应该是这样的。
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)
这篇关于使用indexOf过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文