打印 Javascript split() 数组并将未定义的值转换为字符串
我正在尝试将字符串转换为单词,然后使用 javascript 和 html5 canvas 打印它们。该字符串可以是任意长度,但我使用 50 作为单词的最大值(用空格分隔)。现在我有以下内容来创建数组:
var wordArray = kstring.split(" ", 50);
for(var k = 0; k < wordArray.length; k++)
{
if(typeof wordArray[k] == 'undefined')
wordArray[k] = " .";
}
然后使用:
ctx.fillText(wordArray[0] + " " + wordArray[1] + " " + wordArray[2] + " " + wordArray[3] + " " + wordArray[4], leftOffset, txtHeight);
ctx.fillText(wordArray[5] + " " + wordArray[6] + " " + wordArray[7] + " " + wordArray[8] + " " + wordArray[9], leftOffset, txtHeight+20);
等
进行打印。但是,当打印文本时,任何未定义的值都会打印为“未定义”而不是“”。看来我要以错误的方式检查未定义的值,但我不确定还可以尝试什么。
另外,如果有人对如何实现这个目标有更好的建议(将字符串转换为单词,然后一次打印 5 个单词)。请随时提出一些更好的选择。
谢谢
I am trying to convert a string to words, and then print these using javascript and html5 canvas. The string can be any length, but I am using 50 as a max value of words (separated by a space). Right now I have the following to create the array:
var wordArray = kstring.split(" ", 50);
for(var k = 0; k < wordArray.length; k++)
{
if(typeof wordArray[k] == 'undefined')
wordArray[k] = " .";
}
and then print using:
ctx.fillText(wordArray[0] + " " + wordArray[1] + " " + wordArray[2] + " " + wordArray[3] + " " + wordArray[4], leftOffset, txtHeight);
ctx.fillText(wordArray[5] + " " + wordArray[6] + " " + wordArray[7] + " " + wordArray[8] + " " + wordArray[9], leftOffset, txtHeight+20);
etc.
However, when the text prints, any undefined values print as "undefined" instead of " ." It seems that I am going about checking for the undefined value the wrong way, but I'm not sure what else to try.
Additionally, if anyone has any better suggestions for how to achieve this goal (convert a string to words and then print 5 words at a time). Please feel free to suggest some better options.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.split() 返回的数组中不会有任何未定义的值。您未定义,因为您的打印代码的硬编码索引高于数组中的最高索引。
抱歉,我现在没有时间对此进行测试,也没有时间解释它,除了提到
.slice()
创建一个从源数组中提取范围的新数组,以及.join( )
(显然)与.split()
相反,但也许你可以尝试这样的事情:There won't be any undefined values in the array returned by .split(). You're getting undefined because your print code has hardcoded indexes higher than the highest index in the array.
Sorry, I don't have time right now to test this, or explain it beyond mentioning that
.slice()
creates a new array extracting a range from the source array, and.join()
is (obviously) the opposite of.split()
, but maybe you could try something like this: