我对网页设计和Javascript都很陌生。在设置我的第一个web应用程序时,我遇到了一个我不明白的bug。我认为Javascript在网页中的工作方式肯定是某种东西,或者是一些我对循环不了解的东西。
我试图用js突出显示表的最佳值。只要文件在我的PC上本地运行,我就会生成随机值,并一直按刷新按钮,直到出现错误。出于调试的目的,我现在也使用了console.log函数,但我仍然不明白这是如何发生的.
很大程度上要感谢任何关于这段代码中什么地方可能出错的提示。
// Best value of the week
var table = document.getElementsByTagName('table')[0];
var bestValue = 0;
var bestRow = 0;
for (var i = 1; i < 22; i++) {
if (table.rows[i].childNodes[5].innerHTML > bestValue){
bestValue = table.rows[i].childNodes[5].innerHTML;
console.log(i);
console.log(table.rows[i].childNodes[5].innerHTML);
console.log(bestValue);
bestRow = i;
}
else{
console.log(i);
console.log(table.rows[i].childNodes[5].innerHTML);
console.log(bestValue);
}
}
table.rows[bestRow].childNodes[5].classList.add('bestofweek');

发布于 2020-05-18 06:23:07
正如@AndrewShmig所说,您正在比较字符串和int,应该首先使用parseInt将innerHtml转换为int。要解释为什么不将其解析为int在您的情况下不起作用,
在第一次迭代中:
当将字符串与数字进行比较时,JavaScript将在进行比较时将字符串转换为数字。
因此," 6555“> 0将为6555>0为真,但现在您将使用字符串"6555”分配bestValue,并且它不再是一个int。
接下来的比较是两个字符串之间的比较,这两个字符串是按字母顺序进行的:
"451" > "6555" // false, because 6 comes after 4 alphabetically
"8995" > "6555" // true
"9359" > "8995" // true
// ...
"974" > "9359" // true, because 7 comes after 3 alphabetically
//...现在,您有错误的值作为您的最大值。
发布于 2020-05-18 05:48:29
您在比较字符串,而不是整数。innerHTML返回字符串,而不是数字。
只需添加parseInt:
if (parseInt(table.rows[i].childNodes[5].innerHTML) > bestValue){
bestValue = parseInt(table.rows[i].childNodes[5].innerHTML);https://stackoverflow.com/questions/61862895
复制相似问题