首页 > 解决方案 > 半空间复制分配失败,javascript 堆内存不足

问题描述

我想知道为什么下面的代码会返回内存分配错误?

var countValidWords = function(sentence) {
    let words = [];
    for(let i = 0; i < sentence.length; ++i){
        let word = '';
        while(sentence[i] !== ' '){
            word += sentence[i];
            ++i;
        }
        if(word !== '')
            words.push(word);
    }
    console.log(words);
};

我只是想从输入的句子中构建一组单词(单词可以用多个空格分隔)。

标签: javascript

解决方案


如果句子没有以空格结尾,则while循环永远不会结束,因为它不会检查它是否已经超过了字符串的末尾。结果,您进入一个无限循环undefinedword直到您耗尽内存。

i在那里添加一个在字符串长度范围内的检查。

var countValidWords = function(sentence) {
    let words = [];
    for(let i = 0; i < sentence.length; ++i){
        let word = '';
        while(i < sentence.length && sentence[i] !== ' '){
            word += sentence[i];
            ++i;
        }
        if(word !== '')
            words.push(word);
    }
    console.log(words);
};


推荐阅读