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

And*_*dan 3 javascript firefox xul firefox-addon

这是过去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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码显示的是:"577 <50 + 50"... oO到底是怎么回事577 <100?if语句是真的......似乎无法理解为什么.

Rob*_*b W 6

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

由于offsetContent或是bytesToRead字符串,两个变量都连接在一起:

  • "50" + "50" = "5050"
  • 比较这些值时,字符串将转换为数字,   当然,
    "5050" == 5050       - >     577 < 5050为true.

一些修复代码的方法:

// 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 )
Run Code Online (Sandbox Code Playgroud)