How can I determine the current line number in JavaScript?

前端 未结 8 1700
自闭症患者
自闭症患者 2020-11-27 13:46

Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?

8条回答
  •  旧时难觅i
    2020-11-27 13:51

    A bit more portable between different browsers and browser versions (should work in Firefox, Chrome and IE10+):

    function ln() {
      var e = new Error();
      if (!e.stack) try {
        // IE requires the Error to actually be throw or else the Error's 'stack'
        // property is undefined.
        throw e;
      } catch (e) {
        if (!e.stack) {
          return 0; // IE < 10, likely
        }
      }
      var stack = e.stack.toString().split(/\r\n|\n/);
      // We want our caller's frame. It's index into |stack| depends on the
      // browser and browser version, so we need to search for the second frame:
      var frameRE = /:(\d+):(?:\d+)[^\d]*$/;
      do {
        var frame = stack.shift();
      } while (!frameRE.exec(frame) && stack.length);
      return frameRE.exec(stack.shift())[1];
    }
    

提交回复
热议问题