JavaScript 基础

1. 简介

2. 快速入门

2.1 引入

  • 内部标签

    <script>
        alert('hello, world!');
    </script>
    
  • 外部引入

    <script src="js/first_js.js"></script>
    

2.2 数据类型

  • number

    整数:123
    浮点数:123.1
    科学计数法:1.123e3
    负数:-123
    非数字:NaN
    无限大:Infinity
    
  • 字符串:'abc'"abc"

  • 布尔值:truefalse

  • 逻辑运算:&&||!

  • 比较运算符

    赋值:=
    等于:== (值一样为true)
    绝对等于:=== (类型和值都一样为true
  • 空:null

  • 未定义:undefined

  • 数组

    var arr = [1,2,'hello',null];
    new Array(1,2,'hello',null);
    
  • 对象

    var person = {
        name: "弗罗多",
        age: 50,
        like: ['smoke','drink']
    }
    

2.3 语法

严格检查模式:'use strict';,必须在script代码的第一行。

(1) 定义变量

var score = 60;
let score = 60; // ES6

(2) 条件判断

if (score > 60) {
	...
} else if (score > 80) {
 	...
} else {
	...
}

(3) 控制台输出

console.log('及格');

(4) 弹窗

alert('不及格');

3. 数据类型

3.1 字符串

  • 正常字符串使用 '' 或者 "" 包裹

    let student = 'frodo';
    let level = "不及格";
    
  • 转义字符串使用 "\####"

    let str = "\u4e2d"; // 中
    
  • 多行字符串

    let msg = `
    Time
    
    Time is the currency of your life, spend it wisely
    时间就像是生命的金钱,要学会合理支配
    Don’t let others no matter how well intentioned spend it for you, it’s all you’ve got
    不要让别人为你浪费时间,你该自己去处理你应做的
    In the end, you may falter, but rest assured, time will not
    你最后也许会动摇,但时间不会
    ...
    `;
    
  • 模板字符串

    let msg = `成绩${level}`;
    
  • 字符串长度

    let strLength = student.length;
    
  • 大小写转换

    let strUp = student.toUpperCase();
    let strLow = student.toLowerCase();
    
  • 下标索引

    let dLocal = student.indexOf('d');
    
  • 截取字符串

    let subStr = student.substring(1);	// 1到最后
    let subStr = student.substring(1,4);	// 1到4
    

3.2 数组

  • 数组定义

    let arr = [1,2,3,'frodo'];
    
  • 长度

    let arrLength = arr.length;	// 4
    
  • 下标索引

    let frodoIndex = arr.indexOf('frodo');	// 3
    
  • 数组截取

    let subArr = arr.slice(2);	// [3, 'frodo']
    
  • 尾部添加元素

    /*
     * pushArr = 6
     * arr = [1, 2, 3, 'frodo', 'a', 'b']
     */
    let pushArr = arr.push('a',"b");
    
  • 尾部弹出元素

    /*
     * popArr = 'b'
     * arr = [1, 2, 3, 'frodo', 'a']
     */
    let popArr = arr.pop();
    
  • 头部添加元素

    /*
     * unshArr = 7
     * arr = ['c', 'd', 1, 2, 3, 'frodo', 'a']
     */
    let unshArr = arr.unshift('c','d');
    
  • 头部弹出元素

    /*
     * shArr = 'c'
     * arr = ['d', 1, 2, 3, 'frodo', 'a']
     */
    let shArr = arr.shift();
    
  • 排序

    // arr = ['d', 1, 2, 3, 'frodo', 'a']
    let sortArr = arr.sort();	
    /*
     * arr = [1, 2, 3, 'a', 'd', 'frodo']
     * sortArr = [1, 2, 3, 'a', 'd', 'frodo']
     */
    
  • 元素反转

    // arr = [1, 2, 3, 'a', 'd', 'frodo']
    let reArr = arr.reverse();
    /*
     * arr = ['frodo', 'd', 'a', 3, 2, 1]
     * reArr = ['frodo', 'd', 'a', 3, 2, 1]
     */
    
  • 拼接

    /*
     * arr = ['frodo', 'd', 'a', 3, 2, 1]
     * conArr = ['frodo', 'd', 'a', 3, 2, 1, 'A', 'B']
     */
    let conArr = arr.concat("A","B");
    
  • 连接符

    /*
     * arr = ['frodo', 'd', 'a', 3, 2, 1]
     * joArr = 'frodo-d-a-3-2-1'
     */
    let joArr = arr.join("-");
    
  • 多维数组

    /*
     * (3) [Array(2), Array(2), Array(2)]
     * 0: (2) [1, 2]
     * 1: (2) ['a', 'b']
     * 2: (2) ['壹', '贰']
     * length: 3
     */
    let mulArr = [[1,2],['a','b'],["壹","贰"]];
    

3.3 对象

  • 对象定义

    // person = {name: 'frodo', age: 50, sex: '男', like: 'drink', race: 'Hobbit'}
    let person = {
        name:"frodo",
        age:50,
        like:"drink",
        race: 'Hobbit'
    }
    
  • 对象属性赋值

    // person = {name: 'frodo', age: 50, sex: '男', like: 'smoke', race: 'Hobbit'}
    person.like="smoke";
    
  • 删除对象属性

    /*
     * delper = true
     * person = {name: 'frodo', age: 50, sex: '男', race: 'Hobbit'}
     */
    let delper = delete person.like;
    
  • 添加对象属性

    // person = {name: 'frodo', age: 50, sex: '男', race: 'Hobbit', height: 168}
    person.height = 168;
    
  • 判断属性是否包含在此对象及父对象内

    let ageInPer = 'age' in person;			// true
    let strInPer = 'toString' in person;	// true
    
  • 判断实行是否包含在此对象内

    let perHasSex = person.hasOwnProperty('sex');		// true
    let perHasStr = person.hasOwnProperty('toString');	// false
    

4. 流程控制

4.1 条件判断

if (score > 60) {
	...
} else if (score > 80) {
 	...
} else {
	...
}

4.2 循环

(1) while

while(...) {
	...
}

(2) do while

do{
    ...
} while (...)

(3) for

for (let i = 0; i < 10 ; i++) {
    ...
}
/*
 * array 为数组 value 为元素值
 */
arr.forEach(function (value) {
    ...
});
/*
 * array 为数组 key 为下标
 * array 为对象 key 为关键字
 */
for (const key in array) {
    ...
}
/*
 * arr 为数组 element 为数组元素
 * arr 为 Map,element 为键值对
 * arr 为 set,element 为元素值
 */
for (const element of arr) {
    ...
}

5. Map 和 Set

  • Map

    // score = {'tom' => 100, 'jerry' => 80}
    let score = new Map([['tom',100],['jerry',80]]);
    // tomScore = 100
    let tomScore = score.get('tom');
    // score = addSpikeScore = {'tom' => 100, 'jerry' => 80, 'spike' => 90}
    let addSpikeScore = score.set('spike', 90);	
    /*
     * delSpikeScore = true
     * score = {'tom' => 100, 'jerry' => 80}
     */
    let delSpikeScore = score.delete('spike');
    
  • Set:无须不重复的集合

    // set = {0, 1, 2, 3}
    let set = new Set([0,1,2,3,2,1,0]);
    // set = add = {0, 1, 2, 3, 9}
    let add = set.add(9);
    /*
     * del = true
     * set = {0, 1, 2, 3}
     */
    let del = set.delete(9);
    // has = true
    let has = set.has(3);
    

6. 函数

6.1 函数定义

  • 方式一

    function abs(x) {
        if (x>=0) return x;
        else return -x;
    }
    
  • 方式二

    let abs = function (x) {
        if (x>=0) return x;
        else return -x;
    }
    

6.2 手动抛出异常

function abs(x) {
    if (typeof x !== 'number') throw 'Not a number';
    if (x>=0) return x;
    else return -x;
}

6.3 可变参数

javascript 的函数调用没有参数限制,超出函数定义的参数将会被隐藏,使用 arguments 关键字可以获取到所有的参数。

function abs(x) {
    if (typeof x !== 'number') throw 'Not a number';
    for (let i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
    if (x>=0) return x;
    else return -x;
}

或者可以为函数定义 ...rest 参数获取定义外的参数。

function abs(x,...rest) {
    if (typeof x !== 'number') throw 'Not a number';
    console.log(rest);
    if (x>=0) return x;
    else return -x;
}

6.4 方法

方法就是对象内的函数

let person = {
    name: 'jack',
    birth: 2000,
    age: function () {
        let year = new Date().getFullYear();
        return year-this.birth;
    }
};

this 默认指向当前对象

apply 可更改 this 的指向,使此对象调用另一个对象的方法或属性。

let person = {
    age:function () {
        let year = new Date().getFullYear();
        return year - this.birth;
    }
};
let jack = {
    name: 'jack',
    birth: 2000,
    age: function () {
        let year = new Date().getFullYear();
        return year-this.birth;
    }
};
let apply = person.age.apply(jack);	// 21
let age = person.age();	// NaN

7. 变量

作用域

  • 函数内变量在函数外无效
  • 内部函数可调用外部函数变量
  • 若有同名变量采用就近原则
  • 若调用全局都没有的变量,则会报错
  • js 默认将所有变量的声明提升为全局,因此规范中将所有变量定义为全局变量来保证安全性。

全局变量

定义在函数外的变量即是全局变量,所有的全局变量都会绑定到 window 对象上,因此会有变量冲突问题,规范中通过定义唯一全局变量来解决。

// 唯一全局变量
var app = {};
app.attribute = '属性';
app.function = function (a, ...rest) {
    ...
}

局部变量

同一函数内的代码块中使用 var 定义的变量在代码块外依然有效,js 使用 let 解决局部作用域冲突问题

// vF(12) = '正数'
function vF(a) {
    if (a > 0) {
        var vOut = '正数';
    } else {
        vOut = '负数';
    }
    return vOut;
}
// 报错,ReferenceError: lOut is not defined
function lF(a) {
    if (a > 0) {
        let lOut = '正数';
    } else {
        lOut = '负数';
    }
    return lOut;
}

常量

const PI = 3.14;

8. 标准对象

8.1 Date

let dateTime = new Date();
let fullYear = dateTime.getFullYear();
let month = dateTime.getMonth();
// 日
let date = dateTime.getDate();
// 星期
let day = dateTime.getDay();
let hours = dateTime.getHours();
let minutes = dateTime.getMinutes();
let seconds = dateTime.getSeconds();
// 时间戳
let time = dateTime.getTime();
// 时间戳转换为时间
let transDate = new Date(time);
// 转换为字符串
let dateStr = transDate.toLocaleString();

8.2 JSON

JSON 是一种轻量级的数据交换格式

数组用 [],对象用 {},格式为:key:value

// JSON
let person = {
    name: "json",
    age: 0,
    sex: "男"
}
// perJson = '{"name":"json","age":0,"sex":"男"}'
let perJson = JSON.stringify(person);
// perObj = {name: 'json', age: 0, sex: '男'}
let perObj = JSON.parse(perJson);

8.3 Ajax

9. 面向对象编程

class Person {
    name = '';
    sex = '';
    age = '';
    constructor(name, sex, age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    run () {
        return this.name + " is running...";
    }
}

class Student extends Person {
    like = '';
    constructor(name, sex, age, like) {
        super(name, sex, age);
        this.like = like;
    }

    run() {
        return super.run();
    }
    study() {
        return this.name + " is studying...";
    }
}

let tom = new Student("Tom","man",10,'drink');
console.log(tom);	// Student {name: 'Tom', sex: 'man', age: 10, like: 'drink'}
console.log(tom.study());	// Tom is studying...
console.log(tom.run());		// Tom is running...

10. 操作 BOM 对象

BOM(Brow Object Model)即浏览器模型。

11. 操作 DOM 对象

浏览器网页本质上是一个 DOM 树形结构,对网页的操作相当于操作树形结构的结点。

11.1 获取 DOM 结点

获取 DOM 结点即查找HTML元素

方法描述
document.getElementById(id)通过元素 id 来查找元素
document.getElementsByTagName(name)通过标签名来查找元素
document.getElementsByClassName(name)通过类名来查找元素
<div id="father">
    <h1>Dom</h1>
    <p id="p1">P1</p>
    <p class="p2">P2</p>
</div>
<script>
    'use strict';
    // 获取 DOM 结点
    let h1 = document.getElementsByTagName('h1');
    let p1 = document.getElementById('p1');
    let p2 = document.getElementsByClassName('p2');
</script>

HTML5 之前版本的 document 对象属性

属性描述DOM
document.anchors返回拥有 name 属性的所有 <a> 元素。1
document.applets返回所有 <applet> 元素(HTML5 不建议使用)1
document.baseURI返回文档的绝对基准 URI3
document.body返回 <body> 元素1
document.cookie返回文档的 cookie1
document.doctype返回文档的 doctype3
document.documentElement返回 <html> 元素3
document.documentMode返回浏览器使用的模式3
document.documentURI返回文档的 URI3
document.domain返回文档服务器的域名1
document.domConfig废弃。返回 DOM 配置3
document.embeds返回所有 <embed> 元素3
document.forms返回所有 <form> 元素1
document.head返回 <head> 元素3
document.images返回所有 <img> 元素1
document.implementation返回 DOM 实现3
document.inputEncoding返回文档的编码(字符集)3
document.lastModified返回文档更新的日期和时间3
document.links返回拥有 href 属性的所有 <area><a> 元素1
document.readyState返回文档的(加载)状态3
document.referrer返回引用的 URI(链接文档)1
document.scripts返回所有 <script> 元素3
document.strictErrorChecking返回是否强制执行错误检查3
document.title返回 <title> 元素1
document.URL返回文档的完整 URL1

11.2 更新 DOM 结点

更新结点以及为结点添加属性需通过 ID 获取元素。

方法描述
element.innerHTML = new html content改变元素的 inner HTML
element.attribute = new value改变 HTML 元素的属性值
element.setAttribute(attribute, value)改变 HTML 元素的属性值
element.style.property = new style改变 HTML 元素的样式
<p id="p1">P1</p>
<input id="input"/>
<script>
    // 更新结点
    let p1 = document.getElementById('p1');
    let input = document.getElementById('input');
    p1.innerHTML = '<strong>Inner P1</strong>';
    p1.style.color = 'red';
    input.value = 'BUTTON';
    input.setAttribute('type', 'button');    
</script>

11.3 添加和删除结点

添加、删除结点时需通过 ID 获取本元素,并且要获得其父结点

方法描述
document.createElement(element)创建 HTML 元素
parentElement.removeChild(element)删除 HTML 元素
parentElement.appendChild(element)添加 HTML 元素
parentElement.replaceChild(element)替换 HTML 元素
parentElement.insertBefore(newElement,targetElement)targetElement 前添加 newElement
parentElement.write(text)写入 HTML 输出流

删除元素时,child 是不断变化的。

<div id="father">
    <h1>Dom</h1>
    <p id="p1">P1</p>
    <p id="p2" class="p2">P2</p>
    <input id="input"/>
</div>
<script>
    'use strict';
    // 删除节点
    let p2Id = document.getElementById('p2');
    let parent = p2Id.parentElement;
    parent.removeChild(p2Id);
    // 添加结点
    let input = document.getElementById('input');
    let p3 = document.createElement('p'); // 创建结点
    let p4 = document.createElement('p'); // 创建结点
    p3.id = 'p3';
    p3.innerText = 'P3';
    p4.setAttribute('id', 'p4');
    p4.innerText = 'P4';
    parent.appendChild(p3); // 添加结点
    parent.insertBefore(p4,input);  // input 结点之前插入 p4 结点
    father.replaceChild(p4,p3); // p3 替换为 p4
</script>

11.4 DOM 事件

事件说明
onload进入页面时触发
onunload离开页面时触发
onchange改变 <input> 输入字段内容时触发
onmouseover鼠标悬浮至元素上触发
onmouseout鼠标移开元素时触发
onmousedown在元素上按下鼠标时触发
onmouseup在元素上按下鼠标后释放时触发
onclick鼠标点击完成后触发
<form action="#" method="post">
    <p><span>用户名:</span><input type="text" id="username" name="username" autocomplete="off" οnchange="change()"></p>
    <p><span>密码:</span><input type="password" id="password" name="password" autocomplete="off"></p>
    <button type="button" οnclick="go()" οnmοuseοver="over()" οnmοuseοut="out()" οnmοusedοwn="down()" οnmοuseup="up()">提交</button>
</form>
<script>
    function change() {
        console.log('input 内容改变');
    }
    function over() {
        console.log('鼠标悬浮');
    }
    function out() {
        console.log('鼠标移开');
    }
    function down() {
        console.log('鼠标按下');
    }
    function up() {
        console.log('鼠标释放');
    }
    function go() {
        console.log('鼠标点击完成');
        let name = document.getElementById('username');
        let pw = document.getElementById('password');
        pw.value = md5(pw.value);
    }
</script>

12. jQuery

jQuery 是一个 JavaScript 库,里面包含了大量的 js 函数。

12.1 简单使用

cdn 引入

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

源码下载

在这里插入图片描述

使用方法

$(selector).action()$(选择器).事件(函数体(){...})

选择器包含 css 选择器及 jQuery 自定义的选择器,详见 jQuery API 中文文档

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery</title>
    <!--<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>-->
    <script src="lib/jquery-3.6.0.js"></script>
</head>
<body>

<a ID="test_jQuery"></a>
<script>
    // $(selector).action();
    $('#test_jQuery').click(function () {
        alert('Hello jQuery');
    })
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery</title>
    <!--<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>-->
    <script src="lib/jquery-3.6.0.js"></script>
</head>
<body>

<strong>Mouse : </strong><span id="mouseMove"></span>
<div id="moveDiv" style="width: 500px; height: 500px; border: 1px solid red">
    <p>在此区域移动鼠标</p>
</div>
<script>
    'use strict';
    // 网页加载完毕后响应事件
    $(function () {
        $('#moveDiv').mousemove(function (page) {
            $('#mouseMove').text('x : ' + page.pageX + ' ; y : ' + page.pageY);
        })
    });
</script>

</body>
</html>

12.2 操作 DOM 元素

<ul id="test-ul">
    <li id="java">Java</li>
    <li class="php">PHP</li>
    <li name="python">Python</li>
</ul>
<script>
    'use strict';
    // jQuery 查找 DOM 元素
    let java = $('#java').text();
    let php = $('#test-ul li[class=php]').text();
    let python = $('#test-ul li[name=python]').text();

    // jQuery 操作 DOM 元素
    $('#java').text('JAVA');
    $('#java').html('<strong>Strong JAVA</strong>');
    $('#java').css("color","red");
    $('#test-ul li[class=php]').css({"color":"red", "background":"blue"});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值