[英]Problem With Conditional Check When Two Elements of Array are Same String Value
我遇到了一個問題,如果數組的兩個元素是相同的字符串值,那么它會根據我當前的條件邏輯在打印到控制台的內容中產生問題,如下所示:
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];
for (let t of homeTeamGoalTimes) {
const timeIdx = homeTeamGoalTimes.indexOf(t);
for (let homeScorer of homeTeamScorers) {
const scorerIdx = homeTeamScorers.indexOf(homeScorer);
if (scorerIdx === timeIdx) {
console.log('home scorerIdx:', scorerIdx);
console.log('home goalTime: ', t);
console.log('home timeIdx:', timeIdx);
console.log('home scorer: ', homeScorer);
console.log('-----------');
}
}
}
這是我在控制台中看到的(注意第二個元素組正在重復第一個):
home scorerIdx: 0
home goalTime: 3
home timeIdx: 0
home scorer: John Smith
-----------
home scorerIdx: 0
home goalTime: 3
home timeIdx: 0
home scorer: John Smith
-----------
home scorerIdx: 2
home goalTime: 22
home timeIdx: 2
home scorer: Sam Jones
-----------
當我想看到的是這樣的:
home scorerIdx: 0
home goalTime: 3
home timeIdx: 0
home scorer: John Smith
-----------
home scorerIdx: 1
home goalTime: 10
home timeIdx: 1
home scorer: John Smith
-----------
home scorerIdx: 2
home goalTime: 22
home timeIdx: 2
home scorer: Sam Jones
-----------
我在這里想念什么?
const timeIdx = homeTeamGoalTimes.indexOf('John Smith');
將始終返回 John Smith 的第一個實例。 我建議使用 foreach ,您可以在其中訪問循環中元素的實際索引。
homeTeamGoalTimes.foreach((el, index) => {
const timeIdx = index;
})
您的問題與您的代碼無關,而與您的數據有關。 該數據中有兩個'John Smith'
,這意味着這一行:
const scorerIdx = homeTeamScorers.indexOf(homeScorer);
第一個和第二個'John Smith'
都將為0
。
解決此問題的一種方法是使用具有 ID 屬性的對象來代表您的玩家。 您可以將主隊得分手變量更改為:
const homeTeamScorers = [
{ id: 1, name: 'John Smith'},
{ id: 2, name: 'John Smith'},
{ id: 3, name: 'Sam Jones'}
];
然后將 ID 用於所有索引。 但是,我真的認為您根本不需要兩個索引(即一個用於分數,一個用於團隊成員),我認為這是您真正的問題。
如果你改變:
for (let t of homeTeamGoalTimes) {
const timeIdx = homeTeamGoalTimes.indexOf(t);
for (let homeScorer of homeTeamScorers) {
const scorerIdx = homeTeamScorers.indexOf(homeScorer);
if (scorerIdx === timeIdx) {
// do log
至:
for (let index of homeTeamGoalTimes) {
// do log, and use index for both timeIdx and scorerIdx
那應該簡化您的代碼並解決您的問題。 這應該可以工作,因為您的 arrays:
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];
具有相同的(概念性)索引:在這兩種情況下,索引都表示比賽中的得分索引(在第一個數組中是“誰得分了該目標的索引”,第二個是“該索引的得分是什么時候目標”)。 因此,根本不需要indexOf
。
PS我真的建議這樣做雖然會......
const homeTeamScores = [
{ scorer: 'John Smith', time: 3 },
// ...
因為這樣你每個分數的兩位數據在 object 中固有地鏈接,而不是你的編碼器必須通過索引“鏈接”它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.