我有一个对象数组,它们是作为新类Card实例创建的,还有另一个我要在数组中找到索引并进行拼接的Card类实例:
...
this.cards.push(new Card(suit, rank));
>>>
[
Card { suit: 'Diamonds', rank: 'Jack' },
Card { suit: 'Spades', rank: '3' },
Card { suit: 'Spades', rank: 'Jack' },
Card { suit: 'Diamonds', rank: 'Ace' },
Card { suit: 'Clubs', rank: 'King' },
Card { suit: 'Diamonds', rank: '6' },
Card { suit: 'Spades', rank: '2' },
Card { suit: 'Clubs', rank: '10' },
Card { suit: 'Spades', rank: '7' },
Card { suit: 'Clubs', rank: 'Queen' },
Card { suit: 'Spades', rank: '10' }
]
const match = new Card('Clubs', rank: '10');
>>> Card { suit: 'Clubs', rank: '10' }
在给定数组中搜索匹配项时,函数应返回索引7。 indexOf()方法无法产生预期的结果。我怀疑我是在比较内存中的位置而不是值,但不知道如何解决此问题。
答案 0 :(得分:1)
您只需编写自定义indexOf函数即可检查对象。
function myIndexOf(o) {
for (var i = 0; i < this.cards.length; i++) {
if (this.cards[i].suit == o.suit && this.cards[i].rank == o.rank) {
return i;
}
}
return -1;
}
答案 1 :(得分:1)
您的假设
我怀疑我是在比较内存中的位置而不是值
是正确的。 Array.prototype.findIndex
是您的朋友在这里:
function compareCards(a,b) {
return Object.keys(a).every(key => a[key] === b[key]) && Object.keys(b).every(key => b[key] === a[key]);
}
const arr = [{
suit: 'Diamonds',
rank: 'Jack'
},
{
suit: 'Spades',
rank: '3'
},
{
suit: 'Spades',
rank: 'Jack'
},
{
suit: 'Diamonds',
rank: 'Ace'
},
{
suit: 'Clubs',
rank: 'King'
},
{
suit: 'Diamonds',
rank: '6'
},
{
suit: 'Spades',
rank: '2'
},
{
suit: 'Clubs',
rank: '10'
},
{
suit: 'Spades',
rank: '7'
},
{
suit: 'Clubs',
rank: 'Queen'
},
{
suit: 'Spades',
rank: '10'
}
];
const cardToFind = {
suit: 'Clubs',
rank: 'King'
};
let index = arr.findIndex(card => compareCards(card, cardToFind));
console.log(index);
答案 2 :(得分:1)
您可以使用findIndex方法。它返回通过测试的数组中第一个元素的索引(作为函数提供)。
class Card {
constructor(suit, rank) {
this.suit = suit;
this.rank = rank;
}
}
let cards = [
{ suit: "Diamonds", rank: "Jack" },
{ suit: "Spades", rank: "3" },
{ suit: "Spades", rank: "Jack" },
{ suit: "Diamonds", rank: "Ace" },
{ suit: "Clubs", rank: "King" },
{ suit: "Diamonds", rank: "6" },
{ suit: "Spades", rank: "2" },
{ suit: "Clubs", rank: "10" },
{ suit: "Spades", rank: "7" },
{ suit: "Clubs", rank: "Queen" },
{ suit: "Spades", rank: "10" },
];
const match = (card, cards) => {
return cards.findIndex((x) => x.suit === card.suit && x.rank === card.rank);
};
console.log(match(new Card("Clubs", "10"), cards));