Callstack甚至没有任何递归超过..发生了什么?

时间:2013-11-08 08:51:43

标签: javascript node.js recursion callstack

任何人都知道为什么这可能会产生一个调用堆栈?我甚至没有递归。

错误:

C:\Documents and Settings\j\Desktop\bmrepl\STEAL\dedup.js:7
  this.push.apply(this, rest);
            ^
RangeError: Maximum call stack size exceeded
    at Array.pluck (C:\Documents and Settings\j\Desktop\bmrepl\STEAL\dedup.js:7:13)
    at eatDupe (C:\Documents and Settings\j\Desktop\bmrepl\STEAL\dedup.js:46:15)

    at common (C:\Documents and Settings\j\Desktop\bmrepl\STEAL\dedup.js:39:20)
    at Object.<anonymous> (C:\Documents and Settings\j\Desktop\bmrepl\STEAL\dedup.js:51:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

而且,dedup.js

var input = require('prompt'), sugar = require('sugar');

Array.prototype.pluck = function(i) {
  var el = this[i];
  var rest = this.slice(i + 1 || this.length);
  this.length = i < 0 ? this.length + i : i;
  this.push.apply(this, rest);
  return el;
};




var s = require('fs').readFileSync('NLD_EXSORT.json', {encoding: 'utf8'});
var arr = JSON.parse(s);

if ( arr.filter(function(el){ return el.filter(function(el){ return typeof el != 'string'; }).length != 0; }).length !== 0 ) throw 'nested arrays?'


console.log('all good');

// input.start();







var unq = [];

(function(){

    var dupeDate;

        for(var i = 0; i < arr.length; i++) {

        unq.push(arr[i]);
        while(dupeDate = eatDupe())
            arr[i].push(dupeDate)
        }

    function eatDupe(){
        if (!arr[i+1]) return false;
        if (cmp(arr[i], arr[i+1]) > 2)
            return arr.pluck(i+1).pop();
        else
            return false;
    }

})();

console.log(unq.length);




function cmp(a, b){
  var common = 0;

  while(common < a.length || common < b.length){
    if(a[common] == b[common])
      common++;
    else
      return common;
  }
  if ( a.length == b.length ) return a.length;
  else throw 'CMP_ERR';
}

SO抱怨它的代码太多了,但是我可以把它修剪得更多,我已经这么做了。所以Lorem ipsum dolor也许这不是必要的,idk。

1 个答案:

答案 0 :(得分:0)

我的猜测是[].push()在使用多个参数调用时在内部以某种方式递归。这很容易确认:

var arr = [];

arr.push.apply(arr, new Array(130000));
// RangeError: Maximum call stack size exceeded

为避免此错误,我建议您反复推送,而不是this.push.apply

Array.prototype.pluck = function(i) {
  var el = this[i];
  var rest = this.slice(i + 1 || this.length);
  var k, l;

  this.length = i < 0 ? this.length + i : i;
  this.push.apply(this, rest);

  for(k = 0 l = rest.length; k < l; k++) {
    this.push(rest[k]);
  }

  return el;
};

另外我认为this.splice(i, 1)等同于整个功能(虽然我不完全确定你要做什么)。