JavaScript基础知识详解
JavaScript是一种用于网页开发的脚本语言,也被广泛应用于服务器端开发、移动应用开发等领域。本文将从变量、数据类型、运算符、控制语句、函数等方面详细介绍JavaScript的基础知识。
变量
在JavaScript中,变量是用来存储数据的容器。声明变量时使用关键字var
、let
或const
。
var关键字
使用var
关键字声明的变量是全局或函数级作用域的。
var x = 10;
function foo(){
var y = 20;
console.log(x); // 10
console.log(y); // 20
}
foo();
console.log(x); // 10
console.log(y); // ReferenceError: y is not defined
let关键字
使用let
关键字声明的变量是块级作用域的。
if(true){
let a = 30;
console.log(a); // 30
}
console.log(a); // ReferenceError: a is not defined
const关键字
使用const
关键字声明的变量是常量,一旦赋值之后不能再修改。
const PI = 3.14;
PI = 3.14159; // TypeError: Assignment to constant variable
数据类型
JavaScript中的数据类型包括原始数据类型和引用数据类型。
原始数据类型
原始数据类型包括undefined
、null
、boolean
、number
、string
和symbol
。
let a = undefined;
let b = null;
let c = true;
let d = 123;
let e = 'hello';
let f = Symbol('foo');
引用数据类型
引用数据类型包括object
和function
。
let obj = {name: 'Alice', age: 20};
let func = function(){};
运算符
JavaScript中的运算符包括算术运算符、赋值运算符、比较运算符、逻辑运算符等。
算术运算符
常用的算术运算符包括+
、-
、*
、/
、%
、++
和--
。
let x = 10;
let y = 20;
console.log(x + y); // 30
console.log(x - y); // -10
console.log(x * y); // 200
console.log(y / x); // 2
console.log(y % x); // 0
x++;
console.log(x); // 11
y--;
console.log(y); // 19
赋值运算符
常用的赋值运算符包括=``+=
、-=
、*=
、/=
和%=
。
let x = 10;
x += 5;
console.log(x); // 15
x -= 3;
console.log(x); // 12
x *= 2;
console.log(x); // 24
x /= 3;
console.log(x); // 8
x %= 5;
console.log(x); // 3
控制语句
JavaScript中的控制语句包括条件语句、循环语句和跳转语句。
条件语句
条件语句用于根据不同条件执行不同的代码块,常用的条件语句包括if
语句、else if
语句和switch
语句。
let x = 10;
if(x > 0){
console.log('x is positive');
}else if(x < 0){
console.log('x is negative');
}else{
console.log('x is zero');
}
let y = 'red';
switch(y){
case 'red':
console.log('color is red');
break;
case 'blue':
console.log('color is blue');
break;
default:
console.log('color is unknown');
}
循环语句
循环语句用于重复执行代码块,常用的循环语句包括for
循环、while
循环和do while
循环。
for(let i = 0; i < 5; i++){
console.log(i);
}
let j = 0;
while(j < 5){
console.log(j);
j++;
}
let k = 0;
do{
console.log(k);
k++;
}while(k < 5);
跳转语句
跳转语句用于在代码中跳转至指定位置,常用的跳转语句包括break
、continue
和return
。
for(let i = 0; i < 5; i++){
if(i === 3){
break;
}
console.log(i); // 0 1 2
}
for(let j = 0; j < 5; j++){
if(j === 2){
continue;
}
console.log(j); // 0 1 3 4
}
function add(a, b){
return a + b;
}
console.log(add(3, 5)); // 8
函数
函数是一段可重复调用的代码块,可以接收参数并返回结果。
function greet(name){
console.log('Hello, ' + name);
}
greet('Alice'); // Hello, Alice
function add(a, b){
return a + b;
}
console.log(add(3, 5)); // 8
总结
本文介绍了JavaScript的基础知识,包括变量、数据类型、运算符、控制语句和函数。JavaScript是一门简单灵活的语言,掌握基础知识对于进一步学习和应用JavaScript至关重要。