Javascript 当数组的两个元素是相同的字符串值时,条件检查出现问题
我遇到了一个问题,如果数组的两个元素是相同的字符串值,那么根据我当前的条件逻辑打印到控制台的内容会产生问题,如下所示:Javascript 当数组的两个元素是相同的字符串值时,条件检查出现问题,javascript,arrays,for-loop,Javascript,Arrays,For Loop,我遇到了一个问题,如果数组的两个元素是相同的字符串值,那么根据我当前的条件逻辑打印到控制台的内容会产生问题,如下所示: const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones']; const homeTeamGoalTimes = [3, 10, 22]; for (let t of homeTeamGoalTimes) { const timeIdx = homeTeamGoalTimes.indexOf(t
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: 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
致:
这将简化您的代码并解决您的问题。这应该是可行的,因为您的两个阵列:
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];
具有相同的(概念)索引:在这两种情况下,索引都表示游戏中的得分索引(在第一个数组中是“谁为该进球索引得分”,在第二个数组中是“该进球索引的得分是什么时候”)。因此,实际上根本不需要indexOf
顺便说一句,我真的建议你这么做是
const homeTeamScores = [
{ scorer: 'John Smith', time: 3 },
// ...
因为这样一来,每个分数的两位数据就内在地链接到一个对象中,而不是编码人员必须通过索引“链接”它们。Myb您的日志被堆叠起来,例如,如果在开发者控制台中运行,或者在nodejs环境中运行将不一样。homeTeamGoalTimes数组相对于同时具有两个John Smith的homeTeamScorers数组会是什么样子?上面列出了更新的代码。
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];
const homeTeamScores = [
{ scorer: 'John Smith', time: 3 },
// ...