【四十分钟JavaScript快速入门 | 无废话且清晰流畅 | 手敲键盘 | WEB前端必备程序语言~】https://www.bilibili.com/video/BV15L4y1a7or?p=7&vd_source=950afae367e59984f97924e6e2e7538a
变量与常量
- var:全局变量
- let:可修改变量
- const:不可修改变量
原生数据类型
String、Number、Boolean、null、undifinied
字符串与模板字符串:
const username = 'John';
const age = 30;
console.log('My name is '+username+', my age is '+age+'.');
const hello = `My name is ${username}, my age is ${age}.`;
console.log(hello);
字符串内置属性&函数
const s = 'Hello World!';
// 内置属性
console.log(s.length);
// 内置函数
console.log(s.substring(1,8).toUpperCase());
const st = 'computer, math, it, code';
console.log(st.split(', '));
数组构造方法及内置函数
// 构造函数创建数组(不常用)
const numbers = new Array(1, 2, 3, 4, 5);
// 直接声明数组 可以是不同类型元素
const fruits = ['apples', 'oranges', 'pears', 10, false];
// const数组可以修改内容,只是不能指向另外的数组
// 如 fruits = ['grapes']; 会报错
fruits[1] = 'grapes';
fruits.unshift('straberries'); // 数组头部添加
fruits.push('mangos'); // 数组尾部添加
fruits.pop() // 出栈数组尾部
console.log(Array.isArray(fruits)); // 判断一个对象是否是数组
console.log(fruits);
对象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 main st',
city: 'Boston',
state: 'MA'
}
};
console.log(person.firstName, person.lastName);
const {
firstName,
lastName,
address: { city }
} = person; // 属性拷贝到本地
console.log(city);
person.email('John@mail.com'); // 添加新属性
console.log(person);
对象数组和JSON
const todos = [
{
id: 1,
text: 'Take out trash',
isCompleted: true,
},
{
id: 2,
text: 'Meeting with boss',
isCompleted: true,
},
{
id: 3,
text: 'Dentist appt',
isCompleted: false,
},
];
console.log(todos[1].text);
// 将对象数组转变为JSON格式
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
IF条件
const x = 10;
// 3等号检查数据类型 双等号将两个操作数转换成相同类型比较
if (x === 10) {
console.log('x is 10.');
}
if (x == '10') {
console.log('x is 10.');
}
// 或条件:||
// 与条件:&&
三目运算符
与C语言一样
switch语句
const x = 9;
const color = x > 10 ? 'red' : 'blue';
switch (color) {
case 'red':
console.log('Color is red.');
break;
case 'blue':
console.log('Color is blue.');
break;
default:
console.log('Color is not red or blue.');
}
for和while
const todos = [
{
id: 1,
text: 'Take out trash',
isCompleted: true,
},
{
id: 2,
text: 'Meeting with boss',
isCompleted: true,
},
{
id: 3,
text: 'Dentist appt',
isCompleted: false,
},
];
// 可以采用经典for循环写法
// 也可以采用python等语言的简单for循环写法
for(let todo of todos){
console.log(todo.text);
}
while写法与C无差别。
函数
function 语句用于声明一个函数。
函数声明后,我们可以在需要的时候调用。
在 JavaScript 中,函数是对象,函数也有属性和方法。