javascript - 半空间复制分配失败,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);
};
我只是想从输入的句子中构建一组单词(单词可以用多个空格分隔)。
解决方案
如果句子没有以空格结尾,则while
循环永远不会结束,因为它不会检查它是否已经超过了字符串的末尾。结果,您进入一个无限循环undefined
,word
直到您耗尽内存。
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);
};
推荐阅读
- python - How to find index before the max-value index, idxmax()?
- amazon-web-services - Cloudwatch 警报违反和警报状态更改之间的显着延迟
- javascript - bootstrap 4 导航栏按钮
- scala - SBT confused about Scala types
- python - 如何使用 scikit-learn 对 python 中的数据集执行多元线性回归?
- c++ - Casting int16_t to uint_8t*
- azure-iot-edge - Azure IoT Edge 模块日志位置
- c# - 每个人都可以访问的命名管道
- splunk - Splunk:找出 2 个事件之间的差异
- java - Spring Boot 中所有 @RabbitListener-s 使用 RabbitMQ 消息