Mozilla Firefox扩展开发。 577< 100.这怎么可能?

时间:2012-01-21 11:11:47

标签: javascript firefox firefox-addon xul

这是过去30分钟我无法弄清楚的事情。

var file = Components.classes["@mozilla.org/file/local;1"].
                      createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( sPath );
...
if ( file.fileSize < (offsetContent+bytesToRead) )
{
    wt.BO.log(file.fileSize + "<" + offsetContent + "+" + bytesToRead);
    bytesToRead = file.fileSize - offsetContent;
}

上面的代码显示的是:“577&lt; 50 + 50”... o.O到底是怎样的577&lt; 100? if语句是真的......似乎无法解释原因。

1 个答案:

答案 0 :(得分:6)

加号运算符(+)用于连接字符串,或用于在JavaScript中添加数字。

由于offsetContentbytesToRead是字符串,因此两个变量都是连接的:

  • "50" + "50" = "5050"
  • 比较这些值时,字符串将转换为数字,并且
    "5050" == 5050 - &gt;当然,577 < 5050是正确的。

修复代码的一些方法:

// Substract bytesToRead from both sides
if ( file.fileSize - bytesToRead < offsetContent )
// Or, Turn the comparison operator, and make the right side negative
if ( file.fileSize >= -bytesToRead - offsetContent )
相关问题