简体   繁体   English

console.log和警报返回未定义

[英]console.log and alert returns undefined

This is a basic question about javascript as I am new I would like to try out different things as I used to do in C. So now my Question is when I use 这是一个关于javascript的基本问题,因为我是新手,我想尝试一下以前在C语言中所做的不同事情。所以现在我的问题是当我使用

 console.log(alert()) 

I get the result undefined . 我得到undefined的结果。 Do these functions return no values? 这些函数不返回任何值吗? If they return values what are those and why I can't check them in the console. 如果它们返回值,那是什么以及为什么我无法在控制台中检查它们。 Any help is appreciated. 任何帮助表示赞赏。

Each function in JavaScript returns a value. JavaScript中的每个函数都返回一个值。 If you haven't provided an explicit one, it returns undefined . 如果您未提供显式的,则返回undefined So alert works and its returned value which is undefined is passed to the console.log . 因此, alert可以正常工作,其undefined返回值将传递到console.log

Check this. 检查一下。

 function foo() { } let result = foo(); console.log(result); 

alert always returns undefined , as does console.log . alertconsole.log一样总是返回undefined

If you wanted to save the input from the user in a variable, use prompt : 如果要将用户的输入保存在变量中,请使用prompt

 const str = prompt('Input something'); console.log('str is', str); 

(Or, even better, use a proper modal instead - alert , prompt and confirm are all considered poor practice because they block ) (或者,甚至更好的是,使用适当的模式来代替alertpromptconfirm都被认为是不良做法,因为它们会阻塞

alert(message); 警报(消息);

This shows a message and pauses script execution until the user presses “OK”. 这会显示一条消息,并暂停脚本执行,直到用户按下“确定”为止。 it means it expect a string to be pass as a parameter which will be displayed in the prompts 这意味着它期望将字符串作为参数传递,该字符串将在提示中显示

ref = > https://javascript.info/alert-prompt-confirm . ref => https://javascript.info/alert-prompt-confirm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM