JavaScript基本代码
时间: 2024-02-18 12:30:47 浏览: 78
以下是 JavaScript 的基本代码:
1. 输出 "Hello World":
```javascript
console.log("Hello World");
```
2. 变量声明:
```javascript
var x = 5;
```
3. 条件语句:
```javascript
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is less than or equal to 10");
}
```
4. 循环语句:
```javascript
for (var i = 0; i < 10; i++) {
console.log(i);
}
```
5. 函数声明:
```javascript
function addNumbers(a, b) {
return a + b;
}
var result = addNumbers(5, 10);
console.log(result);
```
6. 事件监听:
```javascript
document.getElementById("myButton").addEventListener("click", function() {
console.log("Button clicked");
});
```
7. 异步请求:
```javascript
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "https://example.com/api/data", true);
xhttp.send();
```
以上是 JavaScript 的基本代码,可以作为入门学习的参考。
阅读全文