问题描述
我想知道您可以分配一个变量来警报吗?它的真正含义和作用是什么?例如,
I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,
var a = alert('test');
我尝试了一下,并在页面加载到变量<$ c的位置时弹出警报当我调用它时,$ c> a 仍然为'undefined'
。我们不是应该使它成为一个内部带有警报的匿名函数,例如
I tried it out, and the alert pops up as soon as the page loads where variable a
remains 'undefined'
when I call it. Aren't we suppose to make it an anonymous function with the alert inside like
var a = function(){ alert('test'); }
是否要触发某些警报?为什么Javascript允许您这样做?
If we want to trigger an alert on something? Why does javascript allow you to do that?
推荐答案
var a = alert('test');
请像其他变量赋值一样考虑该语句。为了执行分配,首先评估右侧。在这种情况下,这是一个函数调用,因此将调用该函数并获取其返回值。在警报的情况下,返回值为未定义
。
Think of this statement like any other variable assignment. In order to perform the assignment, first the right-hand side is evaluated. In this case it's a function call, so the function is called and its return value is obtained. In alert's case, the return value is undefined
. It doesn't return anything.
然后将返回值分配给 a
,因此 a
最终的值为 undefined
。
Then the return value is assigned to a
, so a
ends up with the value undefined
.
语句,显示警告消息。发生这种情况的原因是调用alert()并获取其返回值。
As a side effect of the statement, an alert message is displayed. That happens as a consequence of calling alert() and getting its return value.
function foo(x) {
return x * 2;
}
var a = foo(3);
此代码在结构上与警报调用类似,会导致 a
为6。但是alert()不会返回值。更像这样:
This code is structurally similar to the alert call, and would result in a
being 6. But then alert() doesn't return a value. It's more like this:
function bar(x) {
return;
}
var a = bar(3);
现在 a
是未定义
。
这篇关于JavaScript分配变量以发出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!