function createArray(text){
var arr = [];
var word = null;
for(var i = 0; i<text.length; i++){
if (word == null) {
word = "";
if(text[i] != "," && text[i] != " " && text[i] != "." && text[i] != " "){
word += text[i];
}
else{
arr.push(word);
word = null;
}
}
return arr;
}
var newArray = createArray("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc varius urna sed pede. Suspendisse sit amet lacus. Vivamus consectetuer fringilla ligula. Nunc metus lorem, pretium adipiscing, sollicitudin nec, ultrices quis, nulla. Phasellus nec nulla a eros adipiscing ultrices. Nulla fermentum lectus. Pellentesque ac risus eu massa auctor bibendum. Cras vulputate, nisi eget gravida condimentum, nisl justo tincidunt magna, rutrum imperdiet dui justo vel risus. Donec sit amet pede. Etiam facilisis mauris vitae risus. Ut a neque. Suspendisse augue est, elementum nec, lobortis vel, pulvinar vitae, sapien. Curabitur venenatis enim sit amet sapien. Mauris fermentum interdum eros. Mauris feugiat adipiscing nisl. Donec non nunc. Donec ante enim, eg."
for(var i = 0; i<newArray.length;i++){
document.write(i+ ". "+newArray[i]+"<br />");
}
I have been working on creating a program that can analyze a long piece of text and identify words that only appear once throughout the entire text. I am still in the process of developing this program, but when I tested it to see if it would display each item in the array correctly, the web browser showed a blank screen. In comparison to this alternate code:
function createArray(text){
var arr = [];
var word = "";
for(var i = 0; i<text.length; i++){
if(text[i] != "," && text[i] != " "&& text[i] != "." && text[i] != " "){
word += text[i];
}
else{
arr.push(word);
word = "";
}
}
return arr;
}
for(var i = 0; i<newArray.length;i++){
document.write(i+ ". "+newArray[i]+"<br />");
}
which functions properly. However, if a character sequence such as ". "(period + space) appears, the program adds an empty item to the array due to word = "";
. I attempted to prevent this by using the type null
, as w3schools.com states that "Variables can be emptied by setting the value to null." Nevertheless, using null
results in an error. Why is this?