查找数组中数组元素的索引

时间:2017-03-02 17:59:53

标签: javascript arrays indexof

假设我有一个数组:a.indexOf([2,2])如果我写一个[1],它返回[2,2]。但是,如果我想返回数组元素<html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $("document").ready(function(){ $(".menu-button").click(function(){ $(".side-nav-menu").toggle(100); }); }); </script> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-0"> <div> <a class="btn btn-default menu-button transparent-btn"> <i class="fa fa-bars fa-2x"></i> <i class=""></i> </a> </div> <div class="side-nav-menu btn-group-vertical" style="display:none"> <button class="btn btn-default transparent-btn btn-lg text-left">About</button> <button class="btn btn-default transparent-btn btn-lg text-left">Schedule</button> <button class="btn btn-default transparent-btn btn-lg text-left">Venue</button> <button class="btn btn-default transparent-btn btn-lg text-left">Speakers</button> <button class="btn btn-default transparent-btn btn-lg text-left">Contacts</button> </div> </div> </div> <div> </body> 的索引,如{{1}},则返回-1,但未找到。有没有一种优雅的方法来查找数组中数组元素的索引?

1 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.findIndex()

var index = a.findIndex(function(el) {
  return el[0] == 2 && el[1] === 2
});

var index = a.findIndex(function(el) {
  return el.every(function(n) {return n === 2})
});