繁体   English   中英

当alert()为字符串时,如何将其转换为函数以在javascript中显示警报

[英]when the alert() in string , how to convert it as a function to show the alert in javascript

alert()方法用双引号引起来时,其行为类似于字符串,这意味着在控制台中打印该方法时,控制台屏幕上将显示alert() 但是我想在console.log()有一个alert()时显示一个警告框。 我已经编写了以下代码,但它不能满足我的要求:

var msg="alert("welcome")"
console.log(msg)

当我运行上面的代码时,到控制台的输出是alert("welcome")并且没有创建警报框。 谁能帮我弄清楚如何显示警报框?

谢谢

如果您想做两件事,则需要代码来做两件事。 如果您想用一条语句做两件事,则需要创建一个为您做这两项事情的函数。

function doubleAlert(msg) {
  console.log(msg);
  alert(msg);
}

您应该使用eval()函数:

eval()函数计算或执行一个参数。

如果参数是一个表达式,则eval()将对表达式求值。 如果参数是一个或多个JavaScript语句,则eval()执行这些语句。

 var msg = "alert(\\"welcome\\")"; // Sample message. console.log(msg); // Log to the console regardless. eval(msg); // Evaluate the message as an expression. // Alternatively, regarding your comment about the message being altered, you can do one of the following: var msg = "alert('welcome')"; console.log(msg); eval(msg); // Or: var msg = 'alert("welcome")'; console.log(msg); eval(msg); // Or even: var msg = 'alert(\\'welcome\\')'; console.log(msg); eval(msg); 

尝试这个

function alertAndConsole(msg){
    alert(msg);
    return msg;
}
console.log(alertAndConsole("WELCOME"))

暂无
暂无

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

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