I was wondering why the below code returns a memory allocation error?
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);
};
I'm simply trying to build an array of words from the inputted sentence (words can be separated by more than one space).
If the sentence doesn't end with a space, the while
loop never ends, because it doesn't check if it has gone past the end of the string. As a result, you go into an infinite loop appending undefined
to word
, until you run out of memory.
Add a check that i
is within the string length there.
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); };
while 子句需要检查i
是否越界:
while(i < sentence.length && sentence[i] !== ' ')
How about this? It's not the most optimized version you might find but it works. You had an infinite loop on the while.
var countValidWords = function(sentence) {
let words = [];
let word = ''
for(let i = 0; i < sentence.length; ++i){
if(sentence[i] != '' && sentence[i] != ' '){
word += sentence[i];
}
if(sentence[i] == ' ' || sentence[i + 1] === undefined){
words.push(word);
word = '';
}
}
console.log(words);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.