JavaScript 学习笔记

85 阅读1分钟

官网:www.w3school.com.cn/

1. 引入 JavaScript

有两种常见的引入方式:

  • 内部脚本:在 HTML 文件的 <script> 标签内编写 JavaScript 代码,一般放在 <body> 标签结尾处。
<!DOCTYPE html>
<html lang="en">
<body>
    <!-- 页面内容 -->
    <script>
        console.log('这是一段内部脚本代码');
    </script>
</body>
</html>
  • 外部脚本:创建一个 .js 文件,然后在 HTML 文件中使用 <script> 标签的 src 属性引入。

script.js

console.log('这是外部脚本文件中的代码');

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <!-- 页面内容 -->
    <script src="script.js"></script>
</body>
</html>

2. 变量和数据类型

  • 变量声明:使用 varletconst 声明变量。var 是旧的声明方式,let 用于可重新赋值的变量,const 用于常量(一旦赋值不能再改变)。
var oldVariable = '使用 var 声明';
let newVariable = '使用 let 声明';
const constantValue = '使用 const 声明';
  • 数据类型:常见的数据类型有 number(数字)、string(字符串)、boolean(布尔值)、nullundefinedobject(对象)和 array(数组)。
let num = 10;
let str = 'Hello, World!';
let isTrue = true;
//对象是大括号,数组是中括号
let arr = [1, 2, 3];
//每个属性用逗号隔开,最后一个不要加
let obj = { name: 'John', age: 30 };

字符串

  1. 模板字符串
let name = xinhong";
let age = 18;

let msg = `你好呀,${name}`

输出:你好呀,xinhong
  1. 不可变性
  2. substring方法
[)左闭右开原则
str.substring(1,3)

数组

Array可以包含任意的数据类型

var arr = [1,2,3,4,5]; 
//通过下标取值和赋值
arr[0]
arr[0]=0
  1. 长度
arr.length
  1. indexOf通过元素获得下标索引
arr.indexOf(2)
输出 1
  1. slice()可以截取Array的一部分,返回一个新数组,类似于string中的substring
  2. push(),pop() 尾部
push(): 压入到尾部
pop():弹出尾部的一个元素
  1. 排序sort()
["B","C","A"]
arr.sort()
["A","B","C"]
  1. 元素翻转reverse()
["A","B","C"]
arr.reverse()
["C","B","A"]

对象

对象用{}大括号表示,属性是若干个键值对,所有的键都是字符串,值是任意对象

var 对象名 = {  
    属性名: 属性值,
    属性名: 属性值,
    属性名: 属性值
}

举例
var person = {
  name:"孙悟空",
  age:18,
  gender:"男"
}
  1. 对象赋值
输入 :
person.name = "xinhong"
person.name
输出:
"xinhong"
  1. 动态删减属性,通过delete删除
delete person.name
  1. 动态的添加,直接给新的属性添加值
person.hahah = "hahaha"

Map和Set

Map

var map = new Map([["tom",10],["mary",19]]);

//通过key获得value
var age= map.get('tom');

//设置值
map.set('mon'19);
//删除元素
map.delete('tom')

Set:无序不重复的集合

//增加
var set = new Set([1,3,3,3]);
 //添加
set.add(2);
//判断是否含有每个数字
set.has(3);;

3. 函数

函数是一段可重复使用的代码块。可以使用函数声明或函数表达式来定义函数。

// 函数声明
function add(a, b) {
    return a + b;
}

// 函数表达式
const multiply = function(a, b) {
    return a * b;
};

let result1 = add(2, 3);
let result2 = multiply(4, 5);

函数调用

方法名(参数);

var abs = function(x){  

//解决参数不存在的问题
    if(typeof x!=='number'){  
        throw 'Not a number';
    }
    
    if(x>=0){  
    return x;
    }else{  
    return -x;
    }
    
}

arguments:传递进来的所有参数是一个数组

//可能输入参数不仅是x 比如abs(1,2,3,4)

var abs = function(x){  
    console.log('x=>'+x);
    
    for(var i=0;i<aeguments.length;i++){ 
    console.log(arguments[i]);
    }
    
    if(x>=0){  
    return x;
    }else{  
    return -x;
    }
    
} 

//问题arguments包含所有的参数,我们有时候想用多余的参数来进行附加操作,需要排除已有的参数

rest:获取除已定义参数之外的所有参数,es6的新特性

//rest参数只能写到最后面,必须用...标识

function aaa(a,b,...rest){ 
    console.log("a=>"+a);
    console.log("b=>"+b);
    console.log(rest);
}

箭头函数是 ES6 引入的一种简洁的函数定义方式,

// 无参数
const func1 = () => {
    // 函数体
};

// 单个参数
const func2 = param => {
    // 函数体
};

// 多个参数
const func3 = (param1, param2) => {
    // 函数体
};

// 如果函数体只有一条语句,可以省略大括号和 return 关键字
const func4 = param => param * 2;

方法

定义方法:把函数放到对象里面,对象只放两个东西:属性和方法

var tom = {  
//属性
    name:'tom',
    bith: 2000,
//方法
    age function(){  
        var now = new Date().getFullYear();
        return now-this.birth;
    }
}

//属性
tom.name
//方法,一定要带()
tom.age()

拆开代码

 function getAge(){  
        var now = new Date().getFullYear();
        return now-this.birth;
    }

var tom = {  
//属性
    name:'tom',
    bith: 2000,
    age:getage
}

//属性
tom.name
//方法,一定要带()
tom.age()

Apply

 function getAge(){  
        var now = new Date().getFullYear();
        return now-this.birth;
    }

var tom = {  
//属性
    name:'tom',
    bith: 2000,
    age:getAge
}

var mary= {  
//属性
    name:'mary',
    bith: 2000,
    age:getAge
}

//方法调用
getAge.apply(mary,[]);

4.内部对象

Date

var now = new Date();
now.getFullYear(); //年

JSON

格式:

  • 对象都用{}
  • 数组都用[]
  • 所有的键值对 都是用key:value
 var user = {
    name:"tom",
    age:3,
    sex:'女'
}

//对象转化为json字符串 {"name":"tom","age":3,"sex":"女"}
var userJson = JSON.stringify(user);

//json字符串转化为对象
var user2 = JSON.parse(userJson);

5.面向对象class继承

class继承

定义一个类,属性,方法

//定义一个学生类
class Student{  
    constructor(name){
        this.name=name; 
    }
    
    hello(){  
    alert('hello')
    }
}

class xiaoStudent extends Student{ 
    constructoe(name,grade){  
        super(name);
        this.grade=grade;
    }
    
    myGrade(){ 
    alert('我是一名小学生')
    }
}

var xaioming = new Student('xiaoming');
var xiaohong= new xaioStrudent('xiaohong',1);

xiaoming.hello()

6. 条件语句

用于根据不同条件执行不同的代码块,常见的有 if...elseswitch 语句。

let age = 20;
if (age >= 18) {
    console.log('你已成年');
} else {
    console.log('你还未成年');
}

let day = 'Monday';
switch (day) {
    case 'Monday':
        console.log('今天是周一');
        break;
    case 'Tuesday':
        console.log('今天是周二');
        break;
    default:
        console.log('其他日期');
}

7. 循环语句

用于重复执行代码块,常见的有 forwhiledo...while forEach循环。

// for 循环
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// while 循环
let j = 0;
while (j < 5) {
    console.log(j);
    j++;
}

// do...while 循环
let k = 0;
do {
    console.log(k);
    k++;
} while (k < 5);

//forEach循环
var arr = [1,2,3,4,5,6,7];

//函数
arr.forEach(function(value){
    console.log(value)
})

8.iterator

遍历数组

//通过for of 遍历   / for  in 下标
var arr = [3,4,5]
for(var x of map){  
    console.log(x)
}

遍历map,set

var map = new Map([["tom",10],["mary",19]]);

for(let x of map){  
console.log(x)
}

9.操作BOM对象(重点)

javaScript和浏览器关系?

为了能让js在浏览器中运行

BOM:浏览器对象模型

  • IE 6-11

  • Chrome

  • FireFox

Window

window代表浏览器窗口

Locaiton代表当前页面的URL信息

hash :  ""  host :  "www.baidu.com"  hostname :  "www.baidu.com"  href :  "https://www.baidu.com/index.php?tn=75144485_1_dg&ch=9"  origin :  "https://www.baidu.com"  pathname :  "/index.php"  port :  ""  protocol :  "https:"
//刷新网页
reload: ƒ reload()
//设置新地址
location.assign('地址')

Document(文本内容)代表当前的页面, HTML DOM文档树

获取具体的文档树节点

<div id = 'app'> 
测试
</div>
<script>  
var div = document.getElementById('app');
</script>

获取cookie

document.cookie

劫持cookie原理

<script src="aa.js"></script>
恶意人员获取cookie

服务器端可以设置cookie:httpOnly

10. DOM 操作(重点)

DOM(文档对象模型)允许 JavaScript 操作 HTML 元素。

<!DOCTYPE html>
<html lang="en">
<body>
    <p id="myParagraph">这是一个段落</p>
    <button onclick="changeText()">点击改变文本</button>
    <script>
        function changeText() {
            let paragraph = document.getElementById('myParagraph');
            paragraph.textContent = '文本已改变';
        }
    </script>
</body>
</html>

上述代码中,通过 document.getElementById 方法获取 HTML 元素,然后修改其 textContent 属性。

核心:浏览器就是一个DOM树形结构

  • 更新:更新DOM节点
  • 遍历dom节点:得到DOM节点
  • 删除:删除一个DOM节点
  • 添加:添加一个新的节点

要操作一个DOM节点,就必须先获取这个DOM节点

暂时无法在飞书文档外展示此内容

11.操作表单(验证)

表单的目的:提交信息

获取要提交的信息

<from action="post">
<span>用户名: </span><input type="text id="username">
<from>

<script> 
//得到输入的值
     var input_text = document.getElementById('username');
     
//修改输入的值
input_text.value='123'
</script>

12. 事件处理

可以为 HTML 元素添加事件监听器,当事件触发时执行相应的代码。

<!DOCTYPE html>
<html lang="en">
<body>
    <button id="myButton">点击我</button>
    <script>
        let button = document.getElementById('myButton');
        button.addEventListener('click', function() {
            alert('按钮被点击了');
        });
    </script>
</body>
</html>

13. 数组方法

数组是 JavaScript 中常用的数据结构,有许多实用的方法。

let numbers = [1, 2, 3, 4, 5];
// 数组长度
let length = numbers.length; 
// 向数组末尾添加元素
numbers.push(6); 
// 从数组末尾移除元素
let lastElement = numbers.pop(); 
// 遍历数组
numbers.forEach(function(number) {
    console.log(number);
});

14. 解构

  1. 数组解构

1.1 基本数组解构

从数组中提取元素并赋值给变量,按照数组元素的顺序进行匹配。

const numbers = [10, 20, 30];
// 解构赋值
const [num1, num2, num3] = numbers;
console.log(num1); // 10
console.log(num2); // 20
console.log(num3); // 30

1.2 跳过元素

在解构模式中,可以通过留空来跳过某些不需要的元素。

const fruits = ['apple', 'banana', 'cherry', 'date'];
const [, secondFruit, , fourthFruit] = fruits;
console.log(secondFruit); // banana
console.log(fourthFruit); // date

1.3 默认值

当数组中对应位置的元素不存在时,可以为变量设置默认值。

const colors = ['red'];
const [firstColor, secondColor = 'blue'] = colors;
console.log(firstColor); // red
console.log(secondColor); // blue

1.4 剩余元素

使用剩余运算符 ... 可以将数组中剩余的元素提取到一个新数组中。

const scores = [80, 85, 90, 95];
const [firstScore, ...restScores] = scores;
console.log(firstScore); // 80
console.log(restScores); // [85, 90, 95]
  1. 对象解构

2.1 基本对象解构

根据对象的属性名来提取属性值并赋值给变量。

const user = {
    name: 'Alice',
    age: 30,
    city: 'New York'
};
const { name, age, city } = user;
console.log(name); // Alice
console.log(age); // 30
console.log(city); // New York

2.2 重命名变量

在解构时,可以为属性指定新的变量名,使用 : 来分隔原属性名和新变量名。

const product = {
    title: 'T-shirt',
    price: 19.99
};
const { title: productTitle, price: productPrice } = product;
console.log(productTitle); // T-shirt
console.log(productPrice); // 19.99

2.3 默认值

对象解构也可以设置默认值,当对象中不存在对应属性时,变量将使用默认值。

const settings = {
    theme: 'light'
};
const { theme, fontSize = 16 } = settings;
console.log(theme); // light
console.log(fontSize); // 16

2.4 嵌套对象解构

对于嵌套的对象,可以进行多层解构。

const person = {
    name: 'Bob',
    address: {
        street: '123 Main St',
        city: 'Los Angeles',
        state: 'CA'
    }
};
const { name, address: { street, city, state } } = person;
console.log(name); // Bob
console.log(street); // 123 Main St
console.log(city); // Los Angeles
console.log(state); // CA
  1. 函数参数解构

3.1 对象参数解构

在函数定义中,可以对传入的对象参数进行解构,方便直接使用对象的属性。

function greet({ name, age }) {
    console.log(`Hello, ${name}! You are ${age} years old.`);
}
const personData = {
    name: 'Charlie',
    age: 25
};
greet(personData); // Hello, Charlie! You are 25 years old.

3.2 数组参数解构

函数参数也可以对传入的数组进行解构。

function sum([num1, num2]) {
    return num1 + num2;
}
const numbersArray = [5, 3];
console.log(sum(numbersArray)); // 8