我的问题基于并类似于 this one但有点不同,因为属性名称是可变的。
如何创建一个函数,该函数将返回具有所提供属性的特定值的对象的索引?
function indexOf(propertyName,lookingForValue,array){
//......
return index;
}
所以,
indexOf("token",123123,[
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]);
应返回 1。
我遇到的主要问题是,当我拥有字符串形式的属性名称时,如何检查属性值?
最佳答案
function indexOf(propertyName,lookingForValue,array) {
for (var i in array) {
if (array[i][propertyName] == lookingForValue) {
return i;
}
}
return undefined;
}
编辑:请注意,我故意执行松散类型检查“==”,因为您向此函数提供了一个整数,而在数组中您搜索的值是一个字符串。
关于javascript - 从具有所提供属性的特定值的对象数组中获取索引的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7346270/