您的位置:首页 > Web前端 > JavaScript

[Javascript] Array methods in depth - indexOf

2015-12-30 22:23 756 查看
indexOf is used to search for a value or reference inside of an array. In this lesson we first look at what values are returned when a search is successful vs when it's unsuccessful. Then we move onto a technique that shows how to use the return value to create a boolean flag that can be checked easily. We end by filtering 1 array based on the existence of a value in a whitelist array.

var people = ['Wan', 'John', 'Kate', 'Joe'];
var indexJoe = people.indexOf('Joe');
var findJoe = people.indexOf('Joe') > -1;

console.log(indexJoe, findJoe); //3, true


indexOf can take second params for telling the startLookingIndex:

var people = ['Wan','Joe', 'John', 'Kate'];
var indexJoe = people.indexOf('Joe');
var findJoe = people.indexOf('Joe', 2) > -1;

console.log(indexJoe, findJoe); //1, false

var findJoe = people.indexOf('Joe', 1) > -1;
console.log(indexJoe, findJoe); //1, true


Example:

var whitelist = ['.css', '.js'];

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

var filtered = events.filter(event => {
var ext = event.file.substr(event.file.lastIndexOf('.'));
return whitelist.indexOf(ext) > -1;
});

console.log(filtered);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: