javascript guide

2.dataset

element.dataset.index;
element.dataset.listName; //data-list-name;
dataset["index"];

3.节点操作 node->更好的选择节点

// nodeType,nodeName,nodeValue
node.parentNode;
parentNode.childNodes; //包括文本text  不提倡 nodeType==1 -> element
parentNode.children; //推荐

parentNode.firstChild; //第一个节点,可能是文本节点
parentNode.firstElementChild; //第一个元素 E9才有
parent.children[0];
parentNode.lastChild;
parent.children[parent.children.length - 1];

node.nextSibling; //包含text..
node.previousSibling;
node.nextElementSibling; //下一个兄弟元素节点  兼容性
node.previousElementSibling; //上一个兄弟元素节点 nodeType===1为元素节点

创建节点;
document.createElement("tagName");
先创建在添加节点
:node.appendChild(child);//push
:node.insertBefore(child,element);

删除节点:
node.removeChild(child);

复制节点:
node.cloneNode();//再插入,appendchild,insert; 括号为空||false为浅拷贝只拷贝节点不拷贝内容;
node.cloneNode(ture)

4.创建元素

document.write(); //重绘 不推荐
window.load = function () {
  xxx;
};

innnerHtml; //字符拼接 用数组可提高效率
createElement; //创建很多个时,快

5.DOM 核心 增删改查

appenchild(child);
createelement("d");

removechild;

src, type, style;

getelementbyid;
getelementbyclassname;
getelementbytagname;
queryselector;
queryselectorall;

6.高级事件:

pageshow

e.persisted//true来自缓存

1.注册事件:

传统:
<button onclick='alert("hi")'></button>
btn.onclick=function(){}

监听://推荐
eventTarget.addEventListener(type,listener[,useCapture])//typeof type -> string ;usecapture=true为捕获阶段

attachEvent()//不推荐

2.删除事件

传统.onclick = null

  .removeEventListener("click", fn)

  .detachEvent("onclick", fn);

3.dom 事件流 :捕获,目标,冒泡

js 中只能有捕获或者冒泡阶段
onclick,attchEvent 只能捕获冒泡
onblur,onfoucus,onmouseenter.onmouseleave 没有冒泡

4.事件对象

div.onclick = function (event) {
  console.log(event || window.event);
};
e.target || window.event.srcElement; //触发事件的对象
this; //绑定的对象
e.currentTarget; //ie678
e.type;

5.阻止默认行为:

e.preventDefault();
兼容:e.returnValue;
      return false;

6.防止冒泡:

e.stopPropagation
::e.cancelBuble=true

7.委托事件:

给父类添加事件监听器,点击子类冒泡到父类

e.target.style...

8.Mouse:

docu.addEventListener("contextmenu", function (e) {
  e.preventDefault();
});
selectstart;
mousemove;

e.clientX;
e.clientY;
e.pageX;
e.pageY;
e.screenX;

9.keyEvent:

onkeyup / down / press;
up / down不区分大小写;
press区分但不识别功能键;
keyCode;

BOM

兼容性差

全局对象

1.window.onload(fn);以最后一个为准

2.window.add-L(‘DOMContentLoaded’,fn);

3.window.(on)resize w.innerWidth;//当前屏幕宽度

4.定时器:

setTimeout //只执行一次

setTimeout(callback, 2000); //延迟事件毫秒;default:0
setTimeout("fn()", 2000); //不推荐

起名字:
var timer1=setTimeout(fn,2000);

stop:
window.clearTimeout(timer1)

setInterval(callback,[s]);//不断调用

clearInterval(timer);

this 谁调用指向谁

5.同步与异步

js 是单线程

console.log(1);
setTimeout(function () {
  console.log(3);
}, 1000);
console.log(2);
//r:1,2,3

1.回调函数属于异步任务->任务队列

2.同步任务->主线程执行栈

3.js 代码执行流程:event loop

先同步再异步
先执行栈再执行队列
栈执行完后 队列=true则将任务队列放到执行栈后面执行

example

console.log(1);
setTimeout(function () {
  console.log("end");
}, 0);
console.log(2);

6.location:url


url:protocol://host[:port]/path/   [?query]  #fragment
                 |     |       |          |     |
location.href||host||port||pathname||search||hash||
l.assign();
l.replace();
l.reload([true]);

7.navaigator:userAgent

if (
  navigator.userAgent.match(
    /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrower|JUC|Feenec|wOSBrower|BrowerNG|WebOS|Symbian|Windows Phone)/i
  )
) {
  windows.location.href = ""; //mobile
} else {
  widows.location.href = ""; //pc
}

8.History

history.back();
history.forword();
history.go(1 | 2 | -1);

9.offset 偏移量

element.offsetParent;//return a fatherelement having a position
.offsetTop;
.offsetLeft;// 有无定位
.offsetWidth;//padding+border+margin;   only_read
.offsetHeight;//no 单位

style 更适合修改值 //只能读取行内元素

offset 更适合读取值

10.client

element.clientTop; //上边框
.clientLeft
.clientWidth
.clientHeight//不含边框,不带单位

11.立即执行函数:

优势:独立创建了一个作用域

1(function () {})();
2((function () {})());

12.Scroll

element.scrollTop; //返回被卷去的上侧距离,不带单位
element.scrollLeft;
element.scrollWidth; //返回实际高度,不含边框
div.add - L("scroll", fn);

window.pageYOffset

13.mouseover||mouseenter

mouseover 子盒子也会触发
mouseenter 不会冒泡,只会触发自己的盒子

20.移动端:

1. touch

touchend

touchmove

touchstart

2.touchevent

touches/targetTouches/changedTouches

21.本地存储

localstorage/sessionstorage

.setItem/.getItem/.clear()/removeItem(…)

22.js 闭包

    <script>
        function outer() {
            let a = 1;
            function fn() {
                console.log(a);
            }
            return fn;
        }
        const f = outer();

        //application

        function cnt(){
            let i=0;
            function fn(){
                i++;
                console.log(i);
            }
            return fn;
        }
        let count=cnt();
        count();
    </script>

23.变量提升 var 才有

<script>
  //只提升声明,当前作用下 console.log(num + 'jj');//undefinedjj var num = 33;
</script>

函数也有提升,只提升声明,不调用;

24.动态参数 arguments 伪数组不能用数组方法

function sum(e) {
  let s = 0;
  for (let index = 0; index < arguments.length; index++) {
    s += arguments[index];
  }
  return s;
}
console.log(sum(1, 2));
console.log(sum(1, 2, 3, 4));

25.剩余参数 … 真数组

    <script>
        function sum(...arr) {
            let s=0;
            arr.forEach(function(a){
                s+=a;
            })
            return s;
        }
        console.log(sum(1,2));
        console.log(sum(1,2,3,4));
    </script>

26. …arr 展开数组

let arr1 = [1, 3, 4, 5, 6, 7];
let arr2 = [1, 3, 4, 5, 6, 7];
// ...arr1 === 1,3,5...
console.log(Math.max(...arr1));
console.log(Math.min(...arr2));
let arr = [...arr1, ...arr2];

27.=>函数


<script>
        let fn=name=>({
            name:name
        })
        console.log(fn('Alex'));//name:Alex
    </script>
let sum = (...arr) => {
  let s = 0;
  arr.forEach((x) => (s += x));
  return s;
};
console.log(sum(1, 2));

28.数组结构

let a = 1;
let b = 2;
[a, b] = [b, a]; //a:2,b:1;

let [a = 0, b = 0] = [1, [2, 4]];
console.log(a);
console.log(b);
console.log(b[0]);

let [a2 = 0, [c, d]] = [1, [2, 4]];
console.log(c);
console.log(d);

let getvalue = () => [22, 55];
let [val1, val2] = getvalue();
console.log(val1);

29.对象结构:

const pig = {
  name: "Aelx",
  age: 3,
};
const { name: pigname, age } = pig;
console.log(pigname);
console.log(age);

const goods = [
  {
    goodsName: "huawei",
    price: 1333,
    manager: {
      age: 33,
      address: "beijing",
    },
  },
];
const [{ goodsName, price }] = goods;
console.log(goodsName);
console.log(price);

const [
  {
    manager: { age: myAge, address },
  },
] = goods;
console.log(address);

function a({ data: myData }) {
  return myData.xxx();
}

30.forEach

let arr = [1, 3, "red"];
arr.forEach(function (item, index) {
  console.log(item);
  console.log(index);
});

31.构造函数

//构造函数
// 1.首字母大写  2.无return  3.new为实例化返回一个对象

function Goods(name, price, count) {
  this.name = name;
  this.price = price;
  this.count = count;
}
const { name, price, count } = new Goods("xiaomi", "1999", 20);
console.log(name);
console.log(price);
console.log(count);

32.静态/动态成员:

function Person(name, age) {
  (this.name = name), (this.age = age);
  //实例成员
}
const xm = new Person("xiaoming", 33);
console.log(xm.name); //实例属性
xm.sayHi = () => {
  console.log("xiaomign Hello");
}; //实例方法
Person.canwalk = true; //静态属性
Person.sayBye = () => {
  console.log("byebye");
}; //静态方法
Person.sayBye();
console.log(Person.canwalk);

33.包装类型/引用类型

1.Object

let obj = {
  name: "Alex",
  age: 33,
};
const keys = Object.keys(obj);
const values = Object.values(obj);

console.log(keys);
console.log(values);

const obj2 = {};
Object.assign(obj2, obj);
console.log(obj2);
2.Array
Array 创建
let arr = new Array(1);
let arr2 = new Array(3);
console.log(arr); //[空]
console.log(arr.length); //1
console.log(arr[0]); //undefined
console.log(arr[1]); //undefined

console.log(arr2); //[空x3]
console.log(arr2.length); //3
1.reduce
const arr = [1, 2, 3];
let sum = arr.reduce((prev, current) => prev + current, 10);
console.log(sum);

const arr2 = [
  {
    name: "zhangsan",
    salary: 1000,
  },
  {
    name: "lisi",
    salary: 333,
  },
  {
    name: "wangwu",
    salary: 222,
  },
];
arr2.reduce((prev, current) => {
  return prev + current.salary;
}, 0); //第三个参数不为零则默认数组第一个元素
2.from(arr);
let lis = document.querySelectorAll("ul li"); //NodeList 伪数组
console.log(lis);
let li = Array.from(lis); //转Array
console.log(li);
li.pop();
console.log(li);
3.find(item=>item…)
let arr = [10, 20, 30];
let a = arr.find((item) => item > 10);
console.log(a); //20
let obj = [
  {
    name: "xiaomi",
    price: 3333,
  },
  {
    name: "huawei",
    price: 9999,
  },
];
let huaweiObj = obj.find((item) => item.name === "huawei");
console.log(huaweiObj); //{name: 'huawei',price: 9999}
4.at(-1)

34.原型

//公共属性写在构造函数里
//公共方法写在原型里
function Person(name, age) {
  (this.name = name), (this.age = age);
  //this 指向实例化对象
}
Person.prototype.sing = function () {
  //this 指向实例化对象
  console.log("singing...");
};
let ldh = new Person("liudehua", 33);
ldh.sing();

35.原型添加数组函数:

const arr = [1, 2, 3];
Array.prototype.min = function (arr) {
  return Math.min(...this);
};
Array.prototype.max = function (arr) {
  return Math.max(...this);
};
Array.prototype.sum = function (arr) {
  return this.reduce((prev, current) => prev + current, 0);
};
console.log(arr.min());
console.log(arr.max());
console.log(arr.sum());

36.constructor

function Person(name, age) {
  (this.name = name), (this.age = age);
}
console.log(Person.prototype);
Person.prototype = {
  constructor: Person,
  sing: function () {
    console.log("sing");
  },
  dance: function () {
    console.log(dance);
  },
};
console.log(Person.prototype.constructor === Person);

37.proto

function Person(name, age) {
  (this.name = name), (this.age = age);
}
const xm = new Person("xm", 33);

//__proto__  -> [[Prototype]]  js非标准属性
console.log(xm.__proto__ === Person.prototype);
console.log(xm.constrctor === Person);

38.原型继承

function Person() {
  (this.eyes = 2), (this.head = 1);
}
function Woman() {}
Woman.prototype = new Person();
Woman.prototype.sing = function () {
  console.log("sing");
};
let woman = new Woman();
woman.sing();

function Man() {}
Man.prototype = new Person();
// Man.prototype.sing = function () {
//     console.log('sing');
// }
let man = new Man();
man.sing;

39.原型链

//原型链
//只要是对象就有__proto__,只要是原型就有constructor
function Person() {
  (this.eyes = 2), (this.head = 1);
}
let p1 = new Person();
console.log(p1.eyes);
console.log(p1.__proto__);
console.log(Person.prototype);
console.log(Person.prototype.__proto__);
console.log(Person.prototype.__proto__ === Object.prototype);
console.log(Object.prototype.__proto__ === null);
console.log(Person instanceof Object);

40.deepcopy

//deepcopy  copy
let obj1 = {
  name: "Alex",
  hobby: [1, "sing"],
  family: {
    father: "Mith",
  },
};
let obj2 = obj1;
//共同用一个地址,你改变了他也改变,浅拷贝
console.log(obj2);
obj2.hobby[1] = "Obj2";
console.log(obj2);
console.log(obj1);

// deepcopy三种实现:1.自定义递归函数deepcp,2.loadlash:_.cloneDeep(obj),3.JSON.stringify
// function deepCopy(newObj,oldObj){

//     if()
// }

let newobj = JSON.parse(JSON.stringify(obj1));

41.try/catch

let arr = [];
try {
  let div = document.querySelector(".div");
  function a() {}
} catch (error) {
  debugger;
  throw new Error("Error");
} finally {
  console.log("finally");
}
console.log("after try");

42.this call bind apply

//this:call,apply,bind
//fn.call(thisArg,args*)
//fn.apply(thisArg,[Array])
//fn.bind(thisArg,args*)  不调用 return fn(this不同)
console.log(this); //window
function fn(x, y) {
  console.log(this);
  return x + y;
}
fn(); //window
const obj = {
  name: "Alex",
};
let a = fn.call(obj, 1, 2); //log
console.log(a); //3
let b = fn.apply(obj, [1, 3]);
console.log(b); //4
let c = fn.bind(obj, 3, 5);
console.log(c);
console.log(c(4, 6)); //8

let d = fn.bind(obj);
console.log(c(4, 6)); //10

43.Debunce

44.Throttle 节流

  • 51
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alexmaodali

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值