编程基础/变量示例 JavaScript
外观
< 编程基础
以下示例演示了 JavaScript 中的数据类型、算术运算和输入。
// This program demonstrates variables, literal constants, and data types.
var n;
var s;
var b;
n = 1.23456789012345;
s = "string";
b = true;
output("Number n = " + n);
output("String s = " + s);
output("Boolean b = " + b);
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Number n = 1.23456789012345 String s = string Boolean b = true
每个代码元素代表
//
开始注释var n, s, and b
定义变量;
结束每行 JavaScript 代码i = , d = , s =, b =
将字面值分配给相应的变量output()
调用输出函数function output(text)
定义一个输出函数,该函数检查 JavaScript 环境并根据需要写入当前文档、控制台或标准输出。
// This program demonstrates arithmetic operations.
var a;
var b;
a = 3;
b = 2;
output("a = " + a);
output("b = " + b);
output("a + b = " + (a + b));
output("a - b = " + (a - b));
output("a * b = " + a * b);
output("a / b = " + a / b);
output("a % b = " + (a % b));
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1.5 a % b = 1
每个新的代码元素代表
+, -, *, /, and %
分别表示加法、减法、乘法、除法和模运算。
// This program converts an input Fahrenheit temperature to Celsius.
var fahrenheit;
var celsius;
output("Enter Fahrenheit temperature:");
fahrenheit = input();
celsius = (fahrenheit - 32) * 5 / 9;
output(fahrenheit.toString() + "° Fahrenheit is " + celsius + "° Celsius");
function input(text) {
if (typeof window === 'object') {
return prompt(text)
}
else if (typeof console === 'object') {
const rls = require('readline-sync');
var value = rls.question(text);
return value;
}
else {
output(text);
var isr = new java.io.InputStreamReader(java.lang.System.in);
var br = new java.io.BufferedReader(isr);
var line = br.readLine();
return line.trim();
}
}
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7777777777778° Celsius
每个新的代码元素代表
function input(text)
定义一个函数,该函数检查 JavaScript 环境并从当前窗口、控制台或标准输入读取数据,具体取决于情况。