Javascript学习


JavaScript

JS 入门

  1. 内部标签

  2. 外部引用

数据类型 : 局部变量用 let 定义,少用 var

  • 'use strict' 严格检查模式,必须写在第一行

  • 数字:NaN,Infinity

  • 字符串:‘abc’,“abc”,‘\n’

    // toUpperCase(), substring(1,3), length
    // String 不可变
    let name = 'wang';
    let msg = `你好呀,${name}`;
  • 布尔值:true,false

  • 逻辑运算:&&、||、!

  • 比较运算:=、==(类型不一样,值一样,为true)、===(绝对等于) ;NaN与所有数值不等,包括自己

  • null :空; undefined:未定义

  • JS中数组 不必须是相同类型,越界返回 defined

    var arr = [1,2,3,4,5,6,'1','2'];
    // arr.length  数组长度可以发生变化
    arr.indexOf(2);
    arr.slice(2, 5);
    arr.push('a');    // 尾部添加元素
    arr.pop();        // 尾部弹出元素
    arr.unshift('b'); // 头部添加元素
    arr.shift();      // 头部弹出元素
    arr.sort();
    arr.reverse();
    arr.concat([2,4,'s']); // 不改变原数组
    arr.join('-');
    var arr1 = [[1,2],[3,4],['5','6']];
  • 对象

    var person = {
        name:'wang',
        age:3,
        tag:['js','python','java']
    }
    delete person.age;
    person.haha = 'haha';
    'name' in person;   // true
    name in person;     // false
    'toString' in person;               // true
    person.hasOwnProperty('toString');  // false
    person.hasOwnProperty('name');      // true
  • Set 和 Map

    let set = new Set([1,3,2,1,1,1]);
    set.add(4);
    set.delete(1);
    set.has(3);   // true
    ?
    let map = new Map([['tom',100],['jack',90],['haha',88]]);
    console.log(map.get("haha"));
    map.set("admin", 123);
    map.delete("haha");
    ?
    // for of 遍历数组、set、map
    for (let x of map) {
        console.log(x);
    }

 

函数

两种定义方式:

function abs1(x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
?
?
var abs2 = function (x, ...rest) {
    if (typeof x !== 'number') {
        throw 'not a number';
    }
    // arguments 包含所有传入的参数
    for (let i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
    // rest 获取除了定义之外的所有参数
    console.log(rest);
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

所有变量定义在函数的头部

默认所有全局变量,都自动绑定在window对象下

alert(123);
var old_alert = window.alert;
alert = function (){
    console.log(x);
}
alert(456);
alert = old_alert;
alert(789)
// 结果是弹出 123 和 789, 控制台输出456

为防止误改动全局变量,可以自己设置唯一全局变量

// 唯一全局变量
var wang = {};
// 定义全局变量
wang.name = 'wang';
wang.multiply = function (a, b){    
    return a * b;
}

this 关键字指代 函数调用的对象

function getAge(){
    let now = new Date().getFullYear();
    return now - this.birth;
}
var wang = {
    name : 'wang',
    birth: 1999,
    age: getAge
};
// 控制台输入:
wang.age();  // 23
getAge();    // Uncaught TypeError: Cannot read properties of undefined (reading 'birth')
getAge.apply(wang, []);     // 23

日期函数

var now = new Date();
console.log(now.getFullYear());// 年
console.log(now.getMonth());  // 月  0-11
console.log(now.getDate());   // 日
console.log(now.getDay());    // 星期几
console.log(now.getTime());   // 时间戳
console.log(now.toLocalString());

面向对象编程

原型继承

var xiaoli = {name: 'xiaoli'};
xiaoli.__proto__ = wang;
console.log(xiaoli.age());
?
// object 实例原型为null
Object.prototype.__proto__;     // null

class继承

class Student{
    constructor(name) {
        this.name = name;
    }
    hello(){
        console.log('hello');
    }
}
?
class stu extends Student{
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    hi(){
        console.log('hiiii');
    }
}
var wang1 = new Student("wang");
var wang2 = new stu("wang2", 5);

操作BOM对象

BOM:浏览器对象模型

  • windows

    window.innerHeight
    256
    window.innerWidth
    1280
  • navigator

    navigator.appCodeName
    'Mozilla'
    navigator.appVersion
    navigator.userAgent
  • screen

    screen.width
    1280
    screen.height
    720
  • location

    location :
    host: "www.baidu.com"
    hostname: "www.baidu.com"
    href: "https://www.baidu.com/"
    port: ""
    protocol: "https:"
    reload: ? reload()
    // 设置新的地址
    location.assign('https://...')
  • document

    document.title      // '百度一下,你就知道'
    document.getElementById()
    document.cookie
  • history

    // history表示浏览器的历史记录
    history.back() // 后退
    history.forward() // 前进

操作DOM对象

操作界面的树形结构的节点

   

标题1

   

p1

   

p2

var father = document.getElementById("father");
var children = father.children[0];
var p1 = document.getElementsByClassName("p1");
var h1 = document.getElementsByTagName("h1");

修改文本值

 
var id1 = document.getElementById("id1");
id1.innerText = '324';
id1.innerHTML = '324';
// 修改CSS
id1.style.color= = 'blue'
id1.style.fontSize = '20px'

删除标签

// 通过父节点删除子节点
var father = document.getElementById("father");
father.removeChild(p2);
?
// 通过获取父节点删除子节点
var p2 = document.getElementById('p2');
var f = p2.parentElement;
f.removeChild(p2);
?
// 删除是动态更新的
father.removeChild(father.children[0])
father.removeChild(father.children[0])
father.removeChild(father.children[0])

创建和插入

// 插入标签
father.append(document.getElementById('id1'));
?
// 创建标签script
var myscript = document.createElement('script');
myscript.setAttribute('type','text/javascript');
father.append(myscript);
myscript.innerText = "alert(hello);";
?
// 利用内置style,设置body的背景颜色
var body = document.getElementsByTagName('body');
body[0].setAttribute('style', 'background-color:wheat');
?
// 通过创建标签style,设置body的颜色
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
// 向body里面添加style标签
document.getElementsByTagName('head')[0].appendChild(style);
style.innerHTML = 'body{background-color:wheat}';

还可以获取表单的信息,以及提交表单,一般用 md5 加密密码

json

对象:{}

数组:[]

键值对:key:value

// 对象转化为JSON字符串
var json_person = JSON.stringify(person);
// {"name":"wang","age":3,"tag":["js","python","java"]}
// JSON字符串转化为对象
var obj = JSON.parse(json_person);

JSON字符串 和 JS对象

var obj = {a:'hello', b:'hellob'};
var json = '{"a":"hello", "b":"hellob"}';

JQuery

JQuery 库,封装了大量的 Javascript 函数,可以下载 js 文件,也可以引用 CDN

公式: $(selector). action(),衔接CSS


    
    Title
    


    点击

JQuery 实现鼠标事件:




    
    Title
    
    


?
坐标:
?

衔接 CSS

$('#div1').css({'color':'red','background-color':'wheat'});
$('#div1').css('font-size','40px');
$('#div1').hide();
$('#div1').show();
$('#div1').toggle();

Layer、bootstrap、Element-ui、Ant Design