如何让alert()实现类似console.log的多参数输出效果?
如何在alert中实现类似console.log的多参数输出效果?
alert()和console.log()的参数机制不一样:alert只接受单个参数,你传入的第二个参数typeof m会被直接忽略,这就是为什么你的写法不生效。
要实现类似console.log的多内容输出,有几种简单的方法:
用模板字符串直接拼接所有内容:
alert(`what you input is ${m}, 类型是${typeof m}`);把多个内容放进数组,用
join()方法拼接成字符串:// 用逗号分隔,贴近console.log默认风格 alert([`what you input is ${m}`, typeof m].join(', ')); // 用空格分隔 alert([`what you input is ${m}`, typeof m].join(' '));用字符串加法拼接:
alert(`what you input is ${m}` + ' ' + typeof m);
举个实际运行的例子:
let m = 123; alert([`what you input is ${m}`, typeof m].join(' ')); // 弹出内容:what you input is 123 number
内容的提问来源于stack exchange,提问作者Zhaoyin Fang
相关产品推荐
相关产品推荐

