删除JS对象引用

时间:2017-03-16 18:49:14

标签: javascript scope reference garbage-collection

目前我正在解决JS中的https://www.hackerrank.com/challenges/the-trigram问题。当我针对测试用例输入运行解决方案时 - 它"通过"。但是在提交时 - 它会得到Runtime error

主要思想是我有一个类(Trigram),其中使用input.split(" ").forEach( ... )(在对输入和东西进行标准化之后)我加载所有可能的三元组,与坦诚相比,如果它发生更多次 - 保存到var之外的forEach。 在循环中,对象在let范围内初始化(我在术语中不确定)。

在谷歌搜索后,我发现对象被永远引用(尽管let),所以垃圾收集器不会摆脱它们。这就是我得到Runtime error的原因。

如何摆脱不必要的引用?

// not the exact code
function processData(input) {
    var candid = new Trigram();

    input.split(" ").forEach(function(element, index, array) {
        let obj = new Trigram(array[index], array[index+1], array[index+2]); // I guess, by using array[n] I'm using some kind of ultimate referencing
        if (magic) {
            candid = obj; // with the test case's input it runs twice
        }
    });
}

0 个答案:

没有答案