打印意外的输出,即undefinedranjan [英] Print unexpected output i.e undefinedranjan

查看:74
本文介绍了打印意外的输出,即undefinedranjan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

 var str =ranjan; 
var i;
for(i = 0; i< str.length; i ++)
{
var text;
text =+ text + str [i];
}
console.log(text);





我尝试过:



输出将是undefinedranjan

解决方案

试试这个:

< pre lang =javascript> var str = ranjan ;
var i;
var text = ;
for (i = 0 ; i< str.length; i ++)
{
text + = str [i]; // 等于text = text + str [i];
}
console .log(text);



您的原始代码无效,因为第一次 text =+ text + str [i] 运行, text undefined



另外值得注意的是,在上面的代码块中, var text =; 必须在for循环之外,否则你将每次迭代重新定义 text 为空字符串。


解决方案1已经给你一个解释,这个解决方案告诉你如何看看自己发生了什么。

-----

您的代码没有按照您的预期行事,而且您不会理解为什么!



有一个几乎通用的解决方案:逐步在调试器上运行代码,检查变量。

调试器是这里是为了向您展示您的代码正在做什么以及您的任务是什么o与它应该做的比较。

调试器中没有魔法,它不知道你应该做什么,它没有找到bug,它只是通过显示帮助你你发生了什么事。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行,并在执行时检查变量。

调试器 - 维基百科,免费的百科全书 [ ^ ]

JavaScript调试 [ ^ ]

Chrome DevTools &NBSP; |&NBSP;网络  |  Google Developers [ ^ ]

这里的调试器只显示你的代码正在做什么,你的任务是与它应该做什么进行比较。


var str="ranjan";
var i;
for(i=0;i<str.length;i++)
{
	var text;
	text =""+text+str[i];
}
console.log(text);



What I have tried:

output will be undefinedranjan

解决方案

Try this:

var str="ranjan";
var i;
var text = "";
for(i=0;i<str.length;i++)
{
	text += str[i]; // equal to text = text + str[i];
}
console.log(text);


Your original code doesn't work because at the first time text = "" + text + str[i] runs, text would be undefined.

Also worth noting that in the above code block, var text = ""; must be outside the for loop, otherwise you'd redefine text as empty string each iteration.


Solution 1 already gave you an explanation, this solution tells you how to see what is going on by yourself.
-----
Your code do not behave the way you expect, and you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]
JavaScript Debugging[^]
Chrome DevTools  |  Web  |  Google Developers[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


这篇关于打印意外的输出,即undefinedranjan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆