javascript在数组中查找 [英] javascript find in array
问题描述
我有这样一个数组:
var movies = [
{Name:The Red Violin ,ReleaseYear:1998,导演:FrançoisGirard},
{姓名:Eyes Wide Shut,ReleaseYear:1999,导演:Stanley Kubrick},
{姓名:继承,ReleaseYear:1976,导演:Mauro Bolognini}
];
我想找到1999年发行的电影的位置。
应返回 1
。
最简单的方法是什么?
谢谢。
您必须遍历每个值并检查。
for(var i = 0; i< movies.length; i ++){
if(movies [i]。 ReleaseYear ===1999){
//我是指数
}
}
由于JavaScript最近添加了对大多数常见收集操作的支持这显然是对集合的过滤操作,而你也可以这样做:
var moviesReleasedIn1999 = movies.filter(function(电影){
返回movie.ReleaseYear ==1999;
});
假设您对索引不感兴趣,但对实际数据对象不感兴趣。绝大多数人都不是:)所有浏览器都不支持
.filter
,但你可以添加它您自己的代码库:
https:// developer .mozilla.org / en / JavaScript / Reference / Global_Objects / Array / filter#Compatibility
I have an array like this:
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];
I want to find the location of the movie that's released in 1999.
Should return 1
.
What's the easiest way?
Thanks.
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
这篇关于javascript在数组中查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!