请简述JavaScript的基本语法,并用一个简单的JavaScript函数来实现它的基本语法。
时间: 2024-04-30 09:21:21 浏览: 15
JavaScript的基本语法包括变量声明、条件语句、循环语句、函数定义等。
变量声明使用关键字var、let或const,例如:
```
var a = 1;
let b = "hello";
const c = true;
```
条件语句使用关键字if、else if和else,例如:
```
if (a > 0) {
console.log("a is positive");
} else if (a < 0) {
console.log("a is negative");
} else {
console.log("a is zero");
}
```
循环语句使用关键字for、while和do while,例如:
```
for (let i = 0; i < 10; i++) {
console.log(i);
}
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
let j = 0;
do {
console.log(j);
j++;
} while (j < 10);
```
函数定义使用关键字function,例如:
```
function add(a, b) {
return a + b;
}
console.log(add(1, 2));
```
下面是一个简单的JavaScript函数,实现了将一个字符串中的所有字母变成大写:
```
function toUpperCase(str) {
let result = "";
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
if (charCode >= 97 && charCode <= 122) { // 小写字母
result += String.fromCharCode(charCode - 32);
} else {
result += str.charAt(i);
}
}
return result;
}
console.log(toUpperCase("hello world"));
```