javascript - Find the first same number in the same index on different for loops
问题描述
I want to find the first same number in the same index on different for loops and print 'Yes' if the number match and 'No' if the number does not match.
const x1 = 2;
const v1 = 1;
// 2 + 1 = 3
const x2 = 1;
const v2 = 2;
// 1 + 2 = 3
// Complete the kangaroo function below.
function kangaroo(x1, v1, x2, v2) {
let jump1 = 0;
let jump2 = 0;
let jumps1 = 0;
let jumps2 = 0;
for(let i = x1; i <= 10; i += v1) {
jumps1 = jump1 + i;
console.log(jumps1)
}
console.log('---------------------> Hold on <--------------')
for(let i = x2; i <= 10; i += v2) {
jumps2 = jump2 + i;
console.log(jumps2)
}
if(jumps1 === jumps2) {
console.log('Yes');
} else {
console.log('No');
}
};
kangaroo(x1, v1, x2, v2);
解决方案
Add hese variables before the loops:
const loop1Numbers = {};
const loop2Numbers = {};
Add this inside your first loop:
loop1Numbers[i] = jumps1;
Add this inside your second loop:
loop2Numbers[i] = jumps2;
And finally after the loops you can check if "YES" or "NO":
let isThereAnyNumberEqualInSameIndex = false;
Object.keys(loop1Numbers).forEach(key => {
if (loop1Numbers[key] === loop2Numbers[key]) isThereAnyNumberEqualInSameIndex = true
});
After that - isThereAnyNumberEqualInSameIndex contains true
or false
as you need
推荐阅读
- php - 填充 HTML
- javascript - jsPDF黑色背景和错误样式
- wordpress - 按照 Wordpress 目录中的符号链接?
- c# - 如何修复 Unity 中的数组索引超出范围错误?
- css - 无法在 Angular 中选择绑定属性
- ios - iOS animationWithDuration 链接第一个动画未显示
- c# - 从 Web API 返回的 JSON 格式不正确
- xml - Scala - 处理从文件加载的字符串中的 UTF-8 BOM
- unix - 使用 awk 对 unix 中的文件进行左外连接有点 sql
- c# - 使用 ActionName 属性时如何获取动作名称?