gpt4 book ai didi

javascript - 仅为特定值计算值

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:21 25 4
gpt4 key购买 nike

我有计算当前行和前一行之间差异的函数

在这里

function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {

// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);

var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();

//alert(previousDistance);

var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);

}
}

它适用于所有值

但是我有专栏

<td id="dataType">@data.Datatype</td>

它的值可以是0,1,2

只有 ===2 我才需要计算差异

我试着这样做

function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
var value = $('#dataType').text();
if (value === 2) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);

var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();

//alert(previousDistance);

var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);
}
}
}

但它不起作用。我需要如何正确编写代码?

最佳答案

使用 if (value == 2) 而不是 if (value === 2)

因为相等运算符 === 也会比较操作数的数据类型。

但是值 '2' 的数据类型是 string 而你比较 integer 2

运算符 == 将只比较值 2 == 2,而不比较操作数的数据类型!

关于javascript - 仅为特定值计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com