数组 indexOf 与对象? [英] array indexOf with objects?
本文介绍了数组 indexOf 与对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们可以在 JavaScript 中用 indexOf 匹配数组值.如果匹配,则不会返回 -1.
I know we can match array values with indexOf in JavaScript. If it matches it wont return -1.
var test = [
1, 2, 3
]
// Returns 2
test.indexOf(3);
有没有办法匹配对象?例如?
Is there a way to match objects? For example?
var test = [
{
name: 'Josh'
}
]
// Would ideally return 0, but of course it's -1.
test.indexOf({ name: 'Josh' });
推荐答案
因为这两个对象是不同的(虽然可能是等价的),所以你不能使用 indexOf
.
Since the two objects are distinct (though perhaps equivalent), you can't use indexOf
.
您可以将 findIndex
与回调一起使用,并根据您想要的属性处理匹配.例如,匹配所有可枚举的 props:
You can use findIndex
with a callback, and handle the matching based on the properties you want. For instance, to match on all enumerable props:
var target = {name: 'Josh'};
var targetKeys = Object.keys(target);
var index = test.findIndex(function(entry) {
var keys = Object.keys(entry);
return keys.length == targetKeys.length && keys.every(function(key) {
return target.hasOwnProperty(key) && entry[key] === target[key];
});
});
示例:
var test = [
{
name: 'Josh'
}
];
var target = {name: 'Josh'};
var targetKeys = Object.keys(target);
var index = test.findIndex(function(entry) {
var keys = Object.keys(entry);
return keys.length == targetKeys.length && keys.every(function(key) {
return target.hasOwnProperty(key) && entry[key] === target[key];
});
});
console.log(index);
请注意findIndex
是在 ES2015 中添加的,但完全可填充.
Note that findIndex
was added in ES2015, but is fully polyfillable.
这篇关于数组 indexOf 与对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文