Reputation: 1285
I'm building a JS news ticker that renders strings on a canvas in pixel letters. When the visual length of the rendered string (measured in pixels and represented in the function below by global variable 'calc_w
') exceeds the width (represented by global variable 'w
' in function below) of the canvas, I need to put the second half of the rendered string on the next line. I determine where to break the string up based on the number of spaces in the string (represented below by the variable 'spaces
').
However I cannot figure out why my little function here is returning undefined in the console instead of a number for the spc_indx[i]
variable.
function ins_breaks(str) {
var spaces = 0;
var spc_indx = [];
if (calc_w > w) {
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == " ") {
spaces++;
spc_indx[i] = spaces; //Tells the switch where to cut the string.
}
}
switch (spaces) {
case 4:
//4 spaces = 5 words.
var line2 = str.substr(spc_indx[2]);
//str.replace(' ', '');
console.log(spc_indx[2])
break;
case 5:
console.log(spc_indx[2])
break;
}
}
}
Logging 'spaces
' yielded numbers as expected, yet when I assign spaces to a part of the spc_indx
array, it comes back undefined. Why is spc_indx
array undefined and not a number like I'm expecting to get back?
Here is the fiddle: https://jsfiddle.net/9u3ez6gu/22/
Upvotes: 0
Views: 73