PHP前端开发

js如何输出变量

百变鹏仔 4天前 #JavaScript
文章标签 变量
javascript 变量输出方法包括:console.log(),将变量值打印到控制台。document.write(),将变量值写入到 html 文档。alert(),弹出带有变量值的警报框。return,将值返回到调用函数。

如何输出 JavaScript 变量

输出 JavaScript 变量有以下几种方法:

1. console.log()

console.log() 函数是最常用的输出变量的方法。它将变量值打印到浏览器的控制台中。

console.log(variableName);

2. document.write()

document.write() 函数将变量值写入到当前 HTML 文档中。

document.write(variableName);

3. alert()

alert() 函数弹出带有变量值的警报框。

alert(variableName);

4. return

return 语句将值返回到调用函数的代码中。

function getVariableValue() {  return variableName;}

示例:

let name = "John Doe";// 使用 console.log() 输出变量console.log(name);// 使用 document.write() 输出变量document.write(name);// 使用 alert() 输出变量alert(name);// 使用 return 语句输出变量function getName() {  return name;}

在浏览器中运行这段代码,将在控制台中打印出变量的值,在 HTML 文档中写入变量的值,弹出一个带有变量值的警报框。