JavaScript分配变量以发出警报

编程入门 行业动态 更新时间:2024-10-24 18:21:00
本文介绍了JavaScript分配变量以发出警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道您可以分配一个变量来警报吗?它的真正含义和作用是什么?例如,

I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,

var a = alert('test');

我尝试了一下,并在页面加载到变量 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分配变量以发出警报

本文发布于:2023-11-27 18:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   变量   分配   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!