为什么console.log说undefined,然后是正确的值? [英] Why does console.log say undefined, and then the correct value?

查看:293
本文介绍了为什么console.log说undefined,然后是正确的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  console.log( hi)给出
未定义


console.log(1 + 1)给出
undefined
2

无论是字符串还是整数计算,我都无法定义正确答案。



为什么会收到未定义的消息?有什么好方法可以避免这种情况?

解决方案

控制台将打印评估表达式的结果。自 console.log console.log()的求值结果为未定义。 c $ c>没有显式返回任何内容。



您可以通过许多表达式观察到相同的行为:

 > var x = 1; 
未定义;

变量声明不会产生值,因此再次未定义

作为反例,包含数学运算符的表达式的确会产生一个值,该值会打印到控制台而不是未定义

 > 2 + 2; 
4


console.log("hi") gives 
undefined
hi

console.log(1+1) gives 
undefined
2

Whether it's a string or integer calculation, I get undefined then the correct answer.

Why do I get the undefined message? Is there a good way to avoid it?

解决方案

The console will print the result of evaluating an expression. The result of evaluating console.log() is undefined since console.log does not explicitly return something. It has the side effect of printing to the console.

You can observe the same behaviour with many expressions:

> var x = 1;
undefined;

A variable declaration does not produce a value so again undefined is printed to the console.

As a counter-example, expressions containing mathematical operators do produce a value which is printed to the console instead of undefined:

> 2 + 2;
4

这篇关于为什么console.log说undefined,然后是正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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