简体   繁体   中英

JavaScript Increment Operator isn't working?

So for some reason, when I use the increment operator in this code, it doesn't work. I've verified my variables are numbers.. Not sure what's going on.

var fs = require('fs')
  , bt = require('buffertools')

var start = 0;

fs.readFile(process.argv[2], function(err, data) {
  console.log(data);
  while (bt.indexOf(data, '\n', start)) {
    var nl = bt.indexOf(data, '\n', start); // nl is 40
    console.log(start, nl); // 0, 40
    console.log(data.slice(start, nl)); // works great!

    start = nl++; // reset the offset past that last character..
    console.log(start, typeof start); // start == 40? the heck? 'number'
    process.exit(); // testing
    //console.log(nl, start); 40, 40
  }
});

EDIT ------

And the solution...

"use strict";

var fs = require('fs')
  , bt = require('buffertools');

fs.readFile(process.argv[2], function(err, data) {
  var offset = 0;

  while (true) {
    var nl = bt.indexOf(data, '\n', offset);
    if (nl === -1) break;
    console.log(data.slice(offset, nl));
    offset = ++nl;
  }

  console.log(data.slice(offset));
});

Thanks!

You're looking for ++nl and not nl++ , num++ increments the number and returns the old value .

This is true in many other languages too by the way.


Since you're not changing nl later at all, you can write this as:

    start = nl + 1;

Which is clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM