javascript find in array

匿名 (未验证) 提交于 2019-12-03 00:55:01

问题:

I have an array like this:

I want to find the location of the movie that's released in 1999.

Should return 1.

What's the easiest way?

Thanks.

回答1:

You will have to iterate through each value and check.

for(var i = 0; i < movies.length; i++) {     if (movies[i].ReleaseYear === "1999") {         // i is the index     } } 

Since JavaScript has recently added support for most common collection operations and this is clearly a filter operation on a collection, instead you could also do:

var moviesReleasedIn1999 = movies.filter(function(movie) {     return movie.ReleaseYear == "1999"; }); 

assuming you're not interested in the indexes but the actual data objects. Most people aren't anyways :)

.filter is not supported in all browsers, but you can add it yourself to your code base: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Compatibility



回答2:

Built in? Use loops.

You want to get fancy? Linq to Javascript: http://jslinq.codeplex.com/



回答3:

Something like:

function findMovieIndices(movies, prop, value) {     var result = [];     for(var i = movies.length; i--; ) {         if(movies[i][prop] === value) {             result.push(i); // personally I would return the movie objects         }     }     return result; } 

Usage:

var indices = findMovieIndices(movies, "ReleaseYear", "1999"); 

Maybe this gives you some idea for a more generalized function (if you need it).



回答4:

Since you've also tagged it with jQuery, you could use the 'map' function:

var movies = $.map(movies,function(item,index){     return item.ReleaseYear == 1999 ? index : null;  }); 

This will return an array of indexes for all movies with the year of 1999. If you wanted the movies themselves as an array:

var movies = $.map(movies,function(item){     return item.ReleaseYear == 1999 ? item : null;  }); 


回答5:

If functional style programming is applicable:

_.indexOf(_.pluck(movies, "ReleaseYear"), "1999")

Because it's that simple. The functional toolkit that is underscore.js can be very powerful.

_.indexOf , ._pluck



回答6:

You'll have to create your own searching function.

Of course, this way of doing it actually affects every array you create.. which is maybe not what you want.. you can create your own array object then ...



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!