[Javascript] Array methods in depth - indexOf

本文详细介绍了JavaScript中数组indexOf方法的使用,包括成功搜索与失败搜索时的返回值解释,如何利用返回值创建布尔标志,以及如何基于白名单数组过滤数组元素。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值