[英]Does JavaScript var expression return undefined?
Does the JavaScript expression will return something? JavaScript表达式会返回什么吗?
In the Node.js REPL: 在Node.js REPL中:
> console.log("Hello World")
Hello World
undefined
the undefined
is the JavaScript function return. undefined
是JavaScript函数返回。 Because the JavaScript function always return something. 因为JavaScript函数总是返回某些内容。
But when I try define a variable in REPL: 但是,当我尝试在REPL中定义变量时:
> var x = 11
undefined
There will print a undefined
too. 那里也会打印一个
undefined
。 whether the JavaScript var expression will return something too? JavaScript var表达式是否也会返回某些内容?
Yes, all JavaScript statements have a result, although often it's pretty much useless, and only available using eval
function - at least until do
expressions will be added to the language. 是的,所有JavaScript语句都有结果,尽管通常它几乎是无用的,并且只能通过
eval
函数使用-至少直到do
表达式添加到语言中为止。 For example. 例如。
>>> eval("if (true) 4; else 5;")
4
>>> eval("if (true) 4; else 5;")
5
>>> eval("for (let i = 0; i < 10; i++) 7")
7
>>> eval("for (let i = 0; i < 10; i++) {}")
undefined
>>> eval("var express = 4")
undefined
And so on, the exact values are specified in a language specification. 依此类推,确切的值在语言规范中指定。
When you type something in either browser's console or Node.js REPL, the expression in enclosed in IIFE and executed. 当您在浏览器的控制台或Node.js REPL中键入内容时,该表达式将包含在IIFE中并执行。 This IIFE returns the expression that you entered.
该IIFE返回您输入的表达式。 So if your expression is not returning anything, it prints
undefined
. 因此,如果您的表达式未返回任何内容,它将显示
undefined
。
Imagine you typed: 假设您输入了:
console.log(1)
It is interpreted by Node.js REPL as: Node.js REPL将其解释为:
(function() { return console.log(1) })()
Since it is not returning anything, it simply prints undefined
on console. 由于它不返回任何内容,因此仅在控制台上打印
undefined
内容。
Now if you write a number (eg 1
) in REPL, it is interpreted as: 现在,如果您在REPL中写一个数字(例如
1
),它将被解释为:
(function() { return 1 })()
This will print 1
as return value. 这将打印
1
作为返回值。
HTH 高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.