为什么打印此变量显示提示而不是错误消息?

时间:2019-09-05 09:40:46

标签: javascript prompt console.log

请为什么console.log(theMessage)而不是"You typed" + textTypedIntoPrompt显示弹出提示。

甚至是与此相关的错误消息?

编程新手,只是试图理解为什么该程序以这种方式工作。

谢谢。

var textTypedIntoPrompt = prompt ("Type some text");

var theMessage = "You typed" + textTypedIntoPrompt;

console.log(theMessage);

1 个答案:

答案 0 :(得分:1)

不是console.log会打开弹出提示,而是prompt函数

然后在控制台中完成日志,如下面的摘要所示

var textTypedIntoPrompt = prompt("Type some text");
var theMessage = "You typed : " + textTypedIntoPrompt;
console.log(theMessage);

这是发生的情况的详细说明

var textTypedIntoPrompt =                              
// create a variable named textTypedIntoPrompt
                          prompt("Type some text");    
// open the popup prompt
// the popup prompt freeze the execution until the prompt was confirmed or dismissed
// once the prompt is confirmed/dismissed the function returns
// either what the user wrote (if confirmed) or null (if dismissed)

// when you're here textTypedIntoPrompt contains the input
// and your browser already forgot it came from a prompt

var theMessage =                                       
// then you create a variable named theMessage
                 "You typed : " + textTypedIntoPrompt; 
// and you assign to it the string 'you typed : ' followed by the value of textTypedIntoPrompt
// (which is the return value of prompt) 

console.log(theMessage);
// finally you print this string into the console 
// use ctrl+shift+k to open the console in most browsers

最后是证明console.log的摘录不会打开提示

console.log("didn't open a prompt :)")

此人证明prompt确实打开了提示(正如名字告诉我们的那样)

prompt("I opened a prompt", "you can also set a default value")
// the return value is not saved into a variable so it is lost