需要帮助替换数组中可被 3 和 5 整除的数字



我试图打印数字1-100,同时将数组中可被3整除的任何数字替换为字符串"Ping"和任何能被5整除的数;如果有一个数能被3整除;5 .用"乒乓"字代替。所以3应该是Ping, 5应该是Pong,等等。

这是我的代码,我没有看到我错在哪里:

任何帮助都将非常感激!

const numCount = document.querySelector('.count');
const button = document.querySelector('.num-count');

const numArr = []
for (let i = 1; i <= 100; i++) {
if (numArr[i] % 3 == 0) {
numArr[i] == "Ping"
} else if (numArr[i] % 5 == 0) {
numArr[i] == "Pong"
} else if (numArr[i] % 3 == 0 && numArr[i] % 5 == 0) {
numArr[i] == "PingPong"
};
numArr.push(i);
};
button.addEventListener('click', () => {
numCount.textContent = numArr;
});
.count {
font-size: 12px;
padding-top: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="num-count">Click Me!</button>
<div class="count"></div>

</body>
</html>

有几个问题,这里我们首先用1到100的值初始化数组。

然后在循环中首先检查它是否能被3和5整除,因为其他两个条件包含在其中。

在你的顺序中,它永远不会达到3和5的条件,因为它之前可以被3或5整除。

还要注意===用于比较,=用于赋值。

<!DOCTYPE html>
<html lang="en">
<head>
<style>
.count {
font-size: 12px;
padding-top: 30px;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="num-count">Click Me!</button>
<div class="count"></div>
<script>
const numCount = document.querySelector('.count');
const button = document.querySelector('.num-count');

const numArr = []
// first initialize the array with the values
for (let i = 1; i <= 100; i++) {
numArr[i] = i;
}
for (let i = 1; i <= 100; i++) {
if (numArr[i] % 3 === 0 && numArr[i] % 5 === 0) {
numArr[i] = "PingPong"
} else if (numArr[i] % 5 === 0) {
numArr[i] = "Pong"
} else if (numArr[i] % 3 === 0) {
numArr[i] = "Ping"
};
};
button.addEventListener('click', () => {
numCount.textContent = numArr;
});
</script>
</body>
</html>

let numArr = [];
for (let i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
numArr.push("PingPong");
} else if (i % 3 == 0) {
numArr.push("Ping");
} else if (i % 5 == 0) {
numArr.push("Pong");
}else{
numArr.push(i);
}
}

你的代码有几个问题。

首先,赋值只需要一个=号,所以你没有改变"i"正确。

其次,您检查了numArray在i的索引处的值是否可整除,并且由于您正在动态地向列表添加值,因此在这些索引处没有数字。

第三,在运行过程中改变变量的类型是不好的做法,我建议引入一个输出字符串,这也可以让你减少if的数量,如下所示。

我修改了for循环来工作:

for (let i = 1; i <= 100; i++) {
let output = i.toString()
if (i % 3 === 0) {
output = "Ping"
}
if (i % 5 === 0) {
output += "Pong"
}
numArr.push(output);
}
  1. 删除else if,直接添加if。
  2. 使用赋值操作符赋值而不是相等操作符
for(let i = 1; i <= 100; i++) {
if (numArr[i] % 3 == 0) {
numArr[i] = "Ping"
}
if (numArr[i] % 5 == 0) {
numArr[i] = "Pong"
}
if (numArr[i] % 3 == 0 && numArr[i] % 5 == 0) {
numArr[i] = "PingPong"
}
else{
numArr.push(i);
}
}