函数式编程方法
现在所有时髦的程序员都在使用函数式编程(你好React用户),所以我想给出一个函数式的解决方案。在我看来,它比迄今为止提出的命令式的for
和each
循环要好得多,并且使用ES6语法非常优雅。
更新
现在有一种称为findIndex
的好方法,它接受一个返回true
/false
的函数,根据数组元素是否匹配进行判断(如常规操作,需检查浏览器兼容性)。
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});
使用ES6语法,您可以编写以下内容:
var index = peoples.findIndex(p => p.attr1 == "john")
(旧的)函数式方法
摘要
如果你正在寻找 index
,其中 peoples[index].attr1 == "john"
,请使用以下代码:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
解释
步骤 1
使用 .map()
函数,根据特定的键获取值的数组:
var values = object_array.map(function(o) { return o.your_key; });
上面的行将您从这里带走:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
到这里:
var values = [ "bob", "john", "larry" ];
第二步
现在我们只需要使用.indexOf()
来查找我们想要的键的索引(当然,这也是我们要查找的对象的索引):
var index = values.indexOf(your_value);
解决方案
我们将上述所有内容结合起来:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
或者,如果您更喜欢ES6语法:
var index = peoples.map((o) => o.attr1).indexOf("john");
演示:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);
var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);
var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);