jQuery: Index of element in array where predicate

前端 未结 5 529
小鲜肉
小鲜肉 2020-12-20 13:51

I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and

5条回答
  •  半阙折子戏
    2020-12-20 14:30

    Not really elegant, but a cute trick:

    var index = parseInt(
      $.map(array, function(i, o) { return o.id === target ? i : ''; }).join('')
    );
    

    jQuery doesn't have a lot of functional constructs like that; the philosophy of the library is really focused on the job of DOM wrangling. They won't even add a .reduce() function because nobody can think of a reason it'd be useful to the core functionality.

    The Underscore.js library has a lot of such facilities, and it "plays nice" with jQuery.

提交回复
热议问题