输出 控制台 弹出 dom 数据类型 number、null 、undefied、boolean、string、object 引用类型:array、function
示例 var a=90 ; var b=3.24 ; var c; var h="你好" ; var jk=true ; var ju=null ; var f=new Date (); var hj=[1 ,2 ,3 ,4 ,5 ]; var jk=new Array (7 ).fill (0 ); var lk=function ( ){ console .log ("nh1" ); } console .log (typeof (a)); console .log (typeof (b)); console .log (typeof (c)); console .log (typeof (h)); console .log (typeof (jk)); console .log (typeof (ju)); console .log (typeof (f)); console .log (typeof (hj)); console .log (typeof (lk)); console .log (isNaN ('90' ))
数组 定义数组 var sz=["张三" ,"李四" ,"王五" ,"芙蓉" ];
数组长度 for遍历 for (let i=0 ;i<sz.length ;i++){ }
for of遍历 for (let i of sz){ console .log (i); }
for in遍历 for (let i in sz){ console .log ("下标:" +i+" 值:" +sz[i]); }
定义对象 let cf={ "name" :"张三" , "age" :19 , "address" :"湖南长沙" }
遍历对象 for (let i in cf){ console .log (i); console .log (cf[i]); }
常用方法 push尾部放
var cy=["夯实" ,"立即" ,"嗷" ,"南京" ,"客户" ]console .log (cy.toString ());cy.push ("秸黑" );
pop尾部弹出 unshift头部放 shift头部弹 splice增加删除元素 index 必需。规定从何处添加/删除元素。 该参数是开始插入和(或)删除的数组元素的下标,必须是数字。 howmany 可选。规定应该删除多少元素。必须是数字,但可以是 “0”。 如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。 item1 , …, itemX 可选。要添加到数组的新元素
cy.splice (2 ,1 ); cy.splice (2 ,0 ,"滑块" ,"lohan" ) console .log (cy);
合并 排序 连接 var lj=cy.join ();console .log (lj);
字符串拆成数组 var t="上市,里啊" ;var lk=t.split ("," )console .log (lk);
Dom 通过ID获取 var cf = document .getElementById ("dt" );cf.innerText = "冬天到了!春天还会远嘛!" ;
通过标签获取 var cl = document .getElementsByTagName ("h1" );for (let i = 0 ; i < cl.length ; i++) { cl[i].innerText = "冬天到了第" + (i + 1 ) + "年" ; }
通过class获取 var cln=document .getElementsByClassName ("cf1" );console .log (cln);
通过Name获取 var nj=document .getElementsByName ("c1" );for (let i in nj){ nj[i].innerText ="Name属性获取" ; }
获取一个 var jk=document .querySelector ("h1" )console .log (jk);
获取多个 var jkal=document .querySelectorAll ("h1" );for (let i in jkal){ jkal[i].innerText ="第" +(i)+"年!" ; } var jkna=document .querySelectorAll ("[name=c1]" );console .log (jkna);
操作元素 改内容 hj.innerHTML ="<a href='#'>hello</a>" ; hj.innerText ="<a href='#'>hello</a>" ;
修改属性 var kj=document .querySelector ("img" );kj.src ="31.jpg" ; kj.setAttribute ("price" ,"8888" );
设置样式 var t2=document .querySelector ("#t2" );
事件绑定 dom直接绑定 <button onclick="dme()" >dom直接绑定 点我</button> function dme ( ){ console .log ("哇!金色传说!" ); }
JS绑定 <button id="bt1" >JS 绑定 点我</button> var cf=document .querySelector ("#bt1" ); cf.onclick =function ( ){ console .log ("JS绑定!" ); } cf.onmouseout =function ( ){ console .log ("鼠标移出!" ) }
事件监听绑定 <button id="bt2" >JS 监听器 点我</button> var bt2=document .querySelector ("#bt2" ); bt2.addEventListener ("click" ,function ( ){ console .log ("事件监听!" ); }) bt2.addEventListener ("click" ,function ( ){ console .log ("事件监听2!" ); })
删除监听事件 removeEventListener ("事件名" ,方法名)需要删除监听事件的方法需要提出; 如果是匿名函数则 事件=null ; var bt3=document .querySelector ("#bt3" ); bt3.onclick =function ( ){ console .log ("删除!" ); bt2.removeEventListener ("click" ,dj); cf.onclick =null ; }
留言板 <h1>留言板</h1> <input type ="text" /> <button > 添加</button > <hr /> <script > var bt = document .querySelector ("button" ); bt.onclick = function ( ) { var vau = document .querySelector ("input" ).value ; if (vau == "" ) { alert ("请输入内容!" ); } else { var p = document .createElement ("p" ); var sp = document .createElement ("span" ); sp.innerText = vau; var bton = document .createElement ("button" ); bton.innerText = "删除" ; p.appendChild (sp); p.appendChild (bton); document .querySelector ("body" ).appendChild (p); document .querySelector ("input" ).value = "" ; bton.addEventListener ("click" , function ( ) { this .parentNode .parentNode .removeChild (this .parentNode ); }); } }; </script >
事件冒泡 冒泡 <ul> <li > 1</li > <li > 2</li > <li > 3</li > <li > 4</li > </ul> var ul=document .querySelector ("ul" ); ul.onclick =function ( ){ event.stopPropagation (); var cf=event.srcElement ; }
停止冒泡 阻止事件的默认行为 <a href="https://baidu.com" onclick="cg()" >去百度</a> 让a标签不会跳转 只会执行单击事件 function cg ( ){ event.preventDefault (); alert ("1" ); }
计算器 .js { display : flex; width : 360px; flex-wrap : wrap; padding-left : 0px; margin-top : 0px; } .js li { width : 100px; height : 100px; line-height : 100px; background-color : #717c83; font-size : 20px; font-weight : bold; color : white; margin-top : 0px; } .xs { width : 338px; height : 100px; border : 1px solid #717c83; margin-left : 10px; margin-top : 10px; line-height : 100px; font-size : 40px; font-weight : bold; text-align : right; background-color : #3a4b5a; color : white; } .dxs { margin-left : 70px; border : 1px solid black; width : 360px; height : 570px; background-color : pink; } <div class ="dxs" > <div class ="xs" > </div > <ul class ="js" > <li > 7</li > <li > 8</li > <li > 9</li > <li > 4</li > <li > 5</li > <li > 6</li > <li > 1</li > <li > 2</li > <li > 3</li > <li > 0</li > <li > AC</li > </ul > </div> var ula = document .querySelector (".js" ); ula.onclick = function ( ) { event.stopPropagation (); var fj = event.srcElement ; var jk = fj.innerText ; if (jk == "AC" ) { document .querySelector (".xs" ).innerText = "" ; } else { var xv = document .querySelector (".xs" ).innerText ; document .querySelector (".xs" ).innerText = xv + jk; } };
值类型和引用类型 值类型不可以加属性
引用类型对象类型可以添加属性
var cf = "abscd" ; var xz=new String ("xyh" ); xz.price =800 ; console .log (xz.price ); function newfa ( ){ return "新的字符串!" ; } function func (t ) { t.toString = newfa; } func (cf); func (xz); alert (xz);
逻辑 || 有不为空就是第一个 如果有空则取空 && 不为空就是最后一个 如果有空则就是空
等于(==)和全等于(===) var cf="adb" ;var hj="fjg" var o1=new String ("abc" );var o2=new String ("abc" );console .log (o1===o2);
运算优先级 var i=100 ; alert ((i+=20 ,i*=2 ,'value:' +i));
with var obj=new Object (); obj.name ="temo" ; obj.age =19 ; obj.hi =function ( ){ alert ("nnj" ); } with (obj ){ name="尼玛" ; age=90 ; hi (); } console .log (obj);
二维数组生成表格 var a=[ [1 ,2 ,3 ,4 ], [5 ,6 ,7 ,8 ], [9 ,10 ,11 ,12 ] ] var tab=document .createElement ("table" ); tab.border ="1px" ; tab.width ="50%" tab.cellSpacing ="0px" ; tab.style .height ="300px" ; tab.style .textAlign ="center" for (let i=0 ;i<a.length ;i++){ var tr=tab.insertRow (tab.rows .length ); for (let j=0 ;j<a[i].length ;j++){ var td=tr.insertCell (tr.cells .length ); td.innerText =a[i][j]; } } document .body .appendChild (tab);
二维数组切换下拉框城市 <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <select id="omit" > <option>选择省份</option> </select> <select id="city" ></select> </body> <script> var prov = [ ["湖南省" , "长沙" , "湘潭" , "株洲" , "岳阳" ], ["江西省" , "赣州" , "南昌" , "宜春" , "吉安" ], ["广东省" , "广州" , "白云" , "花都" , "增城" , "越秀" ], ]; var cf = document.querySelector("#omit" ); var ci = document.querySelector("#city" ); window.onload = function () { for (let i = 0 ; i < prov.length; i++) { var moits = new Option (prov[i][0 ], prov[i][0 ]); for (let j = 0 ; j < prov[i].length; j++) { cf.appendChild(moits); cf.onchange = function () { ci.innerHTML = "" ; for (let i = 0 ; i < prov.length; i++) { for (let j = 1 ; j < prov[i].length; j++) { if (cf.value == prov[i][0 ]) { var citys = new Option (prov[i][j], prov[i][j]); ci.appendChild(citys); } } } }; } } }; </script> </html>
前端路由 window .onhashchange =function ( ){ console .log (location.hash ); }
把字符串变成JS变量 函数 事件调用 <button onclick="fun()" >测试函数</button> function fun ( ) { console .log (this ); alert ("函数!" ); }
直接调用 变量调用 var cf = function ( ) { alert ("变量函数!" ); }; cf ();
newFunction调用 var funws = new Function (alert ("newFunction" ));
对象调用 var stu = { age : 19 , studag : function ( ) { this .age += 10 ; alert ("大家看inn达克尼斯看看n" ); }, }; stu.studag (); alert (stu.age ); function Heros (name ) { this .name = name; this .sayhi = function ( ) { alert ("Me:" + this .name ); }; } var cf = new Heros ("张三!" ); cf.sayhi (); function Printer (name ) { this .name = name; this .print = function ( ) { var i=1 ; var xh=setInterval (function ( ){ if (i==10 ){ clearInterval (xh); } console .log ("Name:" +name); i++; },3000 ); }; } var pr1=new Printer ("惠普" ); pr1.print (); function Cat ( ){ this .wigth =20 ; this .eat =function ( ){ for (let i=0 ;i<3 ;i++){ this .wigth +=1 ; } console .log (this .wigth ); } } var catr=new Cat (); catr.eat (); function Car ( ){ this .cost ; this .runn =function (kl ){ this .cost =kl*0.8 ; console .log (this .cost ); } } var Cars =new Car (); Cars .runn (10 );
JS传参数 普通传 function cf (a,b,c ){ console .log (a,b,c); } cf (2 ,5 ,7 );
参数是函数 function kj (name ){ console .log ("Name:" +name); } function nj (fun,msg ){ fun (msg); } nj (kj,"temo" );
改变返回值类型
function kl (t ){ if (t==true ){ return "hello word" ; }else { return {"name" :"李四" } } } var cg=kl (false ); console .log (cg);
返回值返回函数 function km (t ){ return kl (t); } var hj=km (false ); console .log (hj); function vj ( ){ return function (a,b ){ console .log (a+b); } } var kj=vj (); kj (2 ,4 );
通过返回值找出最大的值 let a=[90 ,20 ,10 ,191 ];function find ( ){ var cj={"max" :0 ,"index" :0 } for (let h in a){ if (a[h]>cj.max ){ cj.max =a[h]; cj.index =h; } } return cj; } var p0=find ();console .log (p0);
返回传入的值集合arguments function jz ( ) { var num = 0 ; for (var n = 0 ; n < arguments .length ; n++) { num += arguments [n]; } return num; } alert (jz (1 , 2 , 3 ));
修改原型 对象修改原型 var proper=function (name ){ this .name =name; } proper.prototype .seihi =function ( ){ console .log ("goods" ); } var temo=new proper ("temo" ); temo.seihi ();
string修改原型 var t=new String (" hello " );String .prototype .mytrim =function ( ){ var jk=t.replaceAll (' ' ,'' ); console .log (jk.length ); } t.mytrim ();
函数递归 示例1 function comp (n ){ if (n==1 ){ return 1 ; }else { return comp (n-1 )+n; } } console .log (comp (5 ));
示例25阶层 function jc (n ){ if (n==1 ){ return 1 ; }else { return jc (n-1 )*n; } } console .log (jc (5 ))
示例3斐波拉契数列 function fb (n ){ if (n==1 ){ return 1 ; }else if (n==0 ){ return 0 ; }else { return fb (n-1 )+fb (n-2 ) } } console .log (fb (46 ));
闭包 示例1 function hello (name ){ let city="广州" ; return { gets :function ( ){ var age=18 ; alert ("ME:" +city+name); console .log (age); } } } var hj=hello ("temo" ); hj.gets ();
示例2 function count (nmme ){ var x=1 ; return function ( ){ x++; console .log ("name:" +x); } } var col=count ("temo" ); col (); col ();
示例3 var help=function (x ){ return function ( ){ alert (x); return x; } } var btns=document .querySelectorAll ("button" ); for (var i=0 ;i<btns.length ;i++){ btns[i].onclick =help (i); }
示例4封装 var Person =function ( ){ var name=name; return { getName :function ( ){ return name; }, setName :function (Name ){ return name=Name ; } } } var pers=new Person ("fawcke" ); pers.setName ("重复" ); console .log (pers.getName ())
原型机制 三种对象创建方式
var o1 = {}; var o2 = new Object (); var o3 = new Heros (); function Heros ( ) {} console .log (typeof o1); console .log (typeof o2); console .log (typeof o3);
三种函数创建
function f1 ( ) {} var f2 = function ( ) {}; var f3 = new Function ("alert(1)" ); console .log (typeof f1); console .log (typeof f2); console .log (typeof f3);
function Student (name, age ) { this .name = name; this .age = age; this .hi = function ( ) { alert ("我叫" + this .name + " 我的年龄是" + this .age ); }; } var st1 = new Student ("张胜男" , 19 );var st2 = new Student ("黑马" , 20 );console .log (Student .prototype .constructor ==Student );console .log (st1.constructor == Student ); console .log (st2.constructor == Student ); console .log ("s1_prop_:" +st1.__proto__ );console .log (st1 == st2); console .log (Student .prototype ); Student .prototype .classname = "默认班" ;console .log (st1.classname );Student .prototype .playgame = function ( ) { console .log ("喜欢打game!" ); }; st2.playgame (); console .log (o1.constructor );
JSONP JSONP(JSON with Padding)是 [JSON](https://baike.baidu.com/item/JSON) 的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题
什么情况出现跨域 协议不同 端口不同 IP地址不同 项目名称不同 第一版本 前台直接调用服务器链接地址 <!--服务器不拦截标签--> <!-- <script src="http://localhost:8090/heros/server.js" ></script> --> 后台 新建一个server.js的文件里面写 alert("today is 2021 !" )
第二版本 前台 function locatfn2 (data) { alert(data.msg); } function ycdata (data) { console.log("远程数据:" +data.msg); } <!--用控制器或者servlet代替JS--> <!-- <script src="http://localhost:8090/heros/callback/locatfn" ></script> --> 后台 package com.example.packproject.controller;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.List;@RestController public class JsonpController { @RequestMapping(path = "/callback/{requestname}",method = RequestMethod.GET) public String cf (@PathVariable("requestname") String requestname) throws JsonProcessingException { System.out.println("JSON请求!" ); return requestname+("{'msg':" 你好"}" ) } }
第三版本 function createscript (url,method) { var script=document.createElement("script" ); script.src=url+method; document.querySelector("head" ).appendChild(script); } var url="http://localhost:8090/heros/callback/" ; createscript(url,"locatfn" ); 后台和第二版本一致
第四版本 前台 function createscript (url,method) { var script=document.createElement("script" ); script.src=url+method; document.querySelector("head" ).appendChild(script); } function locatfn (data) { alert(data); } var url="http://localhost:8090/heros/callback/" ; createscript(url,"locatfn" ); 后台 package com.example.packproject.controller;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.List;@RestController public class JsonpController { @RequestMapping(path = "/callback/{requestname}",method = RequestMethod.GET) public String cf (@PathVariable("requestname") String requestname) throws JsonProcessingException { System.out.println("JSON请求!" ); List lin=new ArrayList (); lin.add("张三" ); lin.add("李四" ); lin.add("王五" ); ObjectMapper obj=new ObjectMapper (); String json=obj.writeValueAsString(lin); return requestname+"(" +json+")" ; } }
使用jquery调用 //需要导入jquery
前台: var url = "http://localhost:8090/heros/sheng" ; $(function () { $.ajax({ url: url, async: false , dataType: "jsonp" , success: function (da) { var se = document.querySelector("select" ); for (var i = 0 ; i < da.length; i++) { var cf = new Option (da[i], da[i]); se.appendChild(cf); } }, }); }); 后台: @GetMapping("/sheng") public String unall (String callback) throws JsonProcessingException { System.out.println("省请求" ); List lis=usdao.seall(); List prall=new ArrayList (); for (int i=0 ;i<lis.size();i++) { University un= (University) lis.get(i); String priv=un.getProvince(); prall.add(priv); } ObjectMapper obj=new ObjectMapper (); String json=obj.writeValueAsString(prall); return callback+"(" +json+")" ; }
示例2
前台: function hqs () { var hj=document.querySelector("table" ); if (hj!=null ){ document.body.removeChild(hj); } var indexval = document.querySelector("select" ).value; console.log(indexval); var url = "http://localhost:8090/heros/searchun?unname=" + indexval; $.ajax({ url: url, async: false , dataType: "jsonp" , success: function (da) { var table=document.createElement("table" ); table.border="1px" ; table.cellSpacing="0px" ; table.width="500px" ; table.style.textAlign="center" var trn=document.createElement("tr" ); var wtd1=document.createElement("td" ); wtd1.innerText="学校名称" ; var wtd2=document.createElement("td" ); wtd2.innerText="学校排行" ; var wtd3=document.createElement("td" ); wtd3.innerText="学校地址" ; trn.appendChild(wtd1); trn.appendChild(wtd2); trn.appendChild(wtd3); table.appendChild(trn); for (var i=0 ;i<da.length;i++){ var tr=document.createElement("tr" ); var td=document.createElement("td" ); td.innerText=da[i].schoolName; var td2=document.createElement("td" ); td2.innerText=da[i].ranking; var td3=document.createElement("td" ); td3.innerText=da[i].province; tr.appendChild(td); tr.appendChild(td2); tr.appendChild(td3); table.appendChild(tr); } document.body.appendChild(table); }, }); } 后台: @GetMapping("/searchun") public String serach (String callback,String unname) throws JsonProcessingException { System.out.println("学校:" +unname); System.out.println("查询学校!" ); List lis=usdao.xzs(unname); System.out.println(lis); ObjectMapper obj=new ObjectMapper (); String json=obj.writeValueAsString(lis); return callback+"(" +json+")" ; }
JSOOP高级特征 对象本质可以理解为属性的集合,对象的属性包括数据属性和访问器属性
数据属性 数据属性四大特征 1 、value值2 、writable表示是否可写,默认true ,如果为false ,则表示当前属性只读不可修改3 、enumerable表示是否可枚举,默认true 如果为false ,则在for ...in 中不会被遍历4 、configurable表示是否为可配置的,默认true ,如果为false ,则不能删除,而且不能再改回true
访问器属性 这个属性不包含数据值的位置(get,set) 访问器属性:访问器属性时专门保护数据属性的特殊属性(getting setting) 1 、get方法负责读取变量的值 取值时会调用get方法 2 、set方法负责修改变量的值 设置值会调用set方法 新建定义属性:Object .defineProperty (对象,"属性名(随便命名)" ,{ get :function ( ){ console .log ("查询钱!" ); return "余额:" +this .money ; }, set :function (value ){ console .log ("给stu赋值" ); this .money +=value; } })
var stu={ "id" :1 , "name" :'temo' , "money" :800 } Object .defineProperty (stu,"ccb" ,{ get :function ( ){ console .log ("查询钱!" ); return "余额:" +this .money ; }, set :function (value ){ console .log ("给stu赋值" ); this .money +=value; } }) stu.ccb =500 ; console .log (stu.ccb )
得到属性描述 得到属性描述:Object .getOwnPropertyDescriptor (对象,"属性名" )
var o1={}; //name 、age都是属性值 o1.name="temo"; o1.age=18; o1.study=function(){ alert("hello!"); } //得到属性描述 var oname=Object.getOwnPropertyDescriptor(o1,"name"); console.log(oname); var oage=Object.getOwnPropertyDescriptor(o1,"age"); console.log(oage);
对象输出 console .log (o1.name ); console .log (o1['name' ]); for (var td in o1){ console .log (o1[td]); }
修改属性状态(writable、enumerable、configurable) 修改对象是否可读枚举可配置:Object .defineProperty (对象,"属性名" ,{ writable :false , enumerable :false , configurable :false })
var o1={}; //name 、age都是属性值 o1.name="temo"; o1.age=18; o1.study=function(){ alert("hello!"); } //不可修改 不可枚举 Object.defineProperty(o1,"name",{ //不可修改 writable:false, //不可枚举 enumerable:false, //不可配置 不能删除修改 configurable:false })
严格模式 'use strict' :严格模式 1 、with 不能使用 2 、未声明的变量不能使用 3 、this 默认是undefined 不是windows 非严格模式下对象的本身是本身 4 、只读变量修改报错 5 、函数的行参不可以同名 6 、不能使用arguments 的属性 callee:函数本身 caller :指向调用者
示例 <pre> 以下作业在严格模式下完成: 1 、创建一个猫对象,通过defineProperty给它定义name数据属性,值为大黄,不可修改,可枚举可配置, color数据属性,值为黄色,可修改可枚举可配置,weight访问器属性,可枚举可配置。 2 、创建一个学生stu对象,通过defineProperty定义一个score访问器属性,当运行stu.score = 5 ; 时打印出'成绩进步了5分' ,当运行var s = stu.score ;时打印出‘成绩是95 分’ 3 、创建一个car对象,通过defineProperty定义一个price访问器属性,当运行car.price = 9 ; 时打印出'售车打9折' ,当运行var p = car.price ;时打印出‘价格是999999 元’ </pre> <script > 'use strict' var cat={ "name" :"大黄" , "color" :"黄色" , "tz" :10 }; Object .defineProperty (cat,"name" ,{ writable :false }) Object .defineProperty (cat,"weight" ,{ get :function ( ){ return "体重:" +this .tz ; }, set :function (value ){ this .tz +=value; }, enumerable :true }) cat.weight =20 ; console .log (cat.weight ); var stu={ "cj" :90 } Object .defineProperty (stu,"score" ,{ get :function ( ){ return "成绩:" +this .cj }, set :function (value ){ this .cj +=value console .log ("成绩进步:" +value+"分" ); } }) stu.score =5 ; var s=stu.score ; console .log (s); var car={ "jg" :999990 }; Object .defineProperty (car,"price" ,{ get :function ( ){ return "价格是:" +this .jg }, set :function (value ){ this .jg +=value; console .log ("出售:" +value+"折" ); } }) car.price =9 ; var p = car.price ; console .log (p); </script >
封装继承多态 封装 私有变量私有方法 var Animal =function (name,type ){ var _type=type; var isAnimal=function ( ){ console .log ("这是方法!" +_type); } isAnimal (); } var cat=new Animal ("张胜男" ,"人" );
受保护的 var Dog =function (name,type,age ){ var _type=type; var _age=age; var isDog=function ( ){ console .log ("受保护的" +_type); } Object .defineProperty (this ,"age" ,{ get :function ( ){ console .log ("查看年龄!" ); return _age; }, set :function (val ){ if (val>100 ){ _age=20 ; }else { _age=val; } } }) } var dog=new Dog ("狗" ,"动物" );dog.age =130 ; console .log (dog.age );
公有属性 var Pig =function (name,type ){ this .name =name; this .type =type; this .eat =function ( ){ console .log (name+"在吃东西!" ); } } var pig=new Pig ("猪" ,"动物" );console .log (pig.name ); console .log (pig.type );pig.eat ();
原型属性 console .log (Animal .prototype );Animal .prototype .color ="彩色" ;Animal .prototype .fight =function ( ){ console .log ("打架!" ); } console .log (cat.color );cat.fight (); var birth=new Animal ("鹦鹉" ,"鸟" );birth.fight ();
静态属性 Animal .number =100 ; Animal .count =function ( ){ console .log ("动物总数:" +Animal .number ); } console .log (Animal .number ); Animal .count ();
继承 Object .copy =function (a,b ){ for (arr in b){ a[arr]=b[arr]; } return a; } Object .prototype .exends =function (o ){ return Object .copy (this ,o); } var temo={ name :"temo" , age :18 , r :function ( ){ console .log ("你好" ); } }; var dm={};dm.exends (temo); console .log (dm);console .log (temo);var Shape =function ( ){ this .draw =function ( ){ this ._draw (); } this ._draw =function ( ){ } } var rect=function ( ){};rect.prototype =(new Shape ()).exends ({ width :100 , height :200 , _draw :function ( ){ console .log ("画个圈圈诅咒你!" ); } }); var box=new rect ();box.draw (); console .log (box);var yuan=function ( ){}yuan.prototype =(new Shape ()).exends ({ _draw :function ( ){ console .log ("画圆!" ); } }) var Yuan =new yuan ();Yuan .draw ();
多态 var Circle =function ( ){ this .draw =function ( ){ console .log ("画个圆形!" ); } } var Rect =function ( ){ this .draw =function ( ){ console .log ("画个矩形!" ); } } function dy (obj ){ obj.draw (); } dy (new Rect ())
示例 var Person =function (name,age ){ this .name =name; var _age=age; var account="人类" ; Object .defineProperty (this ,"age" ,{ get :function ( ){ return _age; }, set :function (val ){ var cf=/\d/ ; if (cf.test (val)==true ){ _age=val; }else { _age=19 ; } } }); var showMoney=function ( ){ console .log (account); } this .showMsg =function ( ){ console .log ("name:" +this .name ," age:" +_age); showMoney (); } } var zs=new Person ("张三" ,89 );zs.showMsg (); var Trafic =function (obj ){ obj.runn (); } var Car =function ( ){};Car .prototype .runn =function ( ){ console .log ("开车回家!" ); } Trafic (new Car ());var Bike =function ( ){};Bike .prototype .runn =function ( ){ console .log ("骑自行车回家!" ); }
搭建JQuery框架 对象和数组合并 var stu={ name :"战三" , age :18 } var arr=['temo' ,'zs' ,'lis' ]; Array .prototype .push .apply (stu,arr); for (var ar in stu){ console .log (stu[ar]); }
jquery方法 (function ( ){ var jquery=function (select ){ return new jquery.prototype .Init (select); } jquery.extends =function (obj ){ for (var arr in obj){ this [arr]=obj[arr]; } } jquery.prototype ={ Init :function (select ){ console .log ("选择:" +select); var obj=document .querySelectorAll (select); Array .prototype .push .apply (this ,obj); return this ; }, css :function (csname,cscontext ){ if (cscontext==null || cscontext==undefined ){ return this [0 ].style [csname]; } for (var i=0 ;i<this .length ;i++){ this [i].style [csname]=cscontext; } return this ; }, eq :function (n ){ return this [n]; }, html :function (context ){ if (context==undefined || context==null ){ return this [0 ].innerHTML ; } for (var i=0 ;i<this .length ;i++){ this [i].innerHTML =context; } } } jquery.prototype .Init .prototype =jquery.prototype ; window .$ =jquery; })(); $("h1" ).css ("color" ,"pink" ).css ("font-size" ,"60px" ); console .log ($("h1" ).css ("color" )) $("h1" ).eq (2 ); $("h1" ).html (); $.extends ({ trim :function (str ){ console .log ("去掉空格!" ); var zz=/^\s+|\s+$/g ; return str.replace (zz,'' ); }, }) var cf=" ka " ; var cf=$.trim (cf); console .log ("去空格:" +cf+" " +cf.length );
示例 (function ( ) { var jquery = function (select ) { return new jquery.prototype .Init (select); }; jquery.prototype = { Init : function (select ) { var obj = document .querySelectorAll (select); Array .prototype .push .apply (this , obj); return this ; }, attr : function (arname, arcontext ) { if (typeof arname == "object" ) { for (let j in arname) { console .log (j); for (let i = 0 ; i < this .length ; i++) { console .log (arname[j]); this [i].setAttribute (j, arname[j]); } } } else { if (arcontext == undefined ) { return this [0 ].getAttribute (arname); } for (var i = 0 ; i < this .length ; i++) { this [i].setAttribute (arname, arcontext); } } return this ; }, each : function (obj ) { for (let i = 0 ; i < this .length ; i++) { obj (i, this [i]); } }, }; jquery.prototype .Init .prototype = jquery.prototype ; window .$ = jquery; })(); $(".h6" ).attr ("class" , "h61" ).attr ("name" , "cft" ); $("img" ).attr ({ width : "100px" , height : "50px" }); $("ul li" ).each (function (index, item ) { console .log (index + "----" + item.innerHTML ); });
继承的6种方法 用第5种
function Animal (name ) { this .name = name || "Animal" ; this .sleep = function ( ) { console .log (this .name + "正在睡觉!" ); }; } Animal .prototype .eat = function (food ) { console .log (this .name + "正在吃:" + food); }; var cat = new Animal ("波斯猫" );cat.sleep (); cat.eat ("鱼" ); function Dog ( ) {}Dog .prototype = new Animal ("狗" );var dog = new Dog ();dog.sleep (); dog.eat ("🦴" ); function Ufo ( ) { this .fly = function ( ) { console .log ("反重力飞行!" ); }; } function birth (name ) { Animal .call (this ); Ufo .call (this ); this .name = name; } var br = new birth ("鹦鹉" );br.sleep (); br.fly (); function Pig (name ) { var obj = new Animal (); obj.name = name; return obj; } var pg=new Pig ("猪" );pg.eat ("饭" ); pg.sleep (); function Cat2 (name ){ Animal .call (this ); this .name =name; } Cat2 .prototype =new Animal ();var cat2=new Cat2 ("小白" );cat2.sleep (); cat2.eat ("🐟" ); function Cat3 (name ){ Animal .call (this ); this .name =name; } (function ( ){ var supper=function ( ){ } supper.prototype =Animal .prototype ; Cat3 .prototype =new supper; })(); var cat3=new Cat3 ("小黑" );cat3.sleep (); cat3.eat ("小米" );
let定义 { var i=10 ; let k=20 ; } console .log ("17:" +i); var arr=[]; for (let i=1 ;i<20 ;i++){ arr[i]=function ( ){ console .log ("23:" +i); } } arr[6 ]();
const定义 const studn={}; studn.name ="展示干" ; console .log (studn.name );
箭头函数 //函数的参数只有一个时可以省略括号 无参数时不可以省略
//函数体里面只有一行的时候 可以省略花括号 {}
无参数无返回值 let fn1 =( )=>console .log ("无参数无返回值" );let fn11 =( )=>{ console .log ("无参数无返回值" ) } fn1 ();
有参数无返回值 let fn2 =name=>console .log ("有参数无返回值:" +name);fn2 ("张三" );let fn3 =(name,age )=>console .log ("有参数无返回值:" +name+" " +age);fn3 ("散" ,12 );let fn62 =(a,b )=>{ return a+b; }
无参数有返回值 let fn4 =( )=>45 ;console .log ("无参数有返回值:" +fn4 ());let fn5=function ( ){ return 50 ; }
有参数有返回值 let fn5 =(a,b )=>a+b;console .log ("有参数有返回值:" +fn5 (5 ,1 ))let fn6=function (a,b ){ return a+b; }
函数返回对象 函数的返回值是对象 let fn7=function ( ){ let obj={'name' :'提莫' ,"age" :19 }; return obj; } let cf=fn7 (); console .log (cf.name ); let fn71 =( )=>{ return {'name' :'提莫' ,"age" :19 }; } let cf2=fn71 (); console .log (cf2.age ); let fn72 =( )=>({'name' :'提莫' ,"age" :19 }); let cf3=fn72 (); console .log (cf3.age );
函数的参数默认值 function hello (text ){ text=text || "无名" ; console .log ("你好:" +text); } hello ("狗头" ); hello ();
展开模式 … function num3xj (x,y,z ){ console .log (x,y,z); } num3xj (1 ,3 ,5 ); let arnum=[45 ,67 ,1 ]; num3xj (...arnum);
rest模式 function renum1 (...arr ){ console .log (arr) } renum1 (1 ,23 ,56 );
对象解构 et stu={ name :"站撒" , age :21 , sex :'男' } let {name,age,sex}=stu; console .log (name,age,sex) let {name :a,age :b,sex :c}=stu; console .log (a,b,c);
数组解构 var szjg=[1 ,25 ,6 ,8 ]; console .log (szjg[0 ]); console .log (szjg[1 ]); console .log (szjg[2 ]); let [x,y,z,h]=szjg; console .log (x,y,z,h);
声明对象简写 重构 let name1="张胜男干" ; let age1=19 ; let set1="男" ; let stuj={name1,age1,set1}; console .log (stuj);
for of let nums=["num1" ,"num2" ,"num3" ,"num3" ]; Array .prototype .fn =function ( ){} for (let i=0 ;i<nums;i++){ console .log (nums[i]); } for (let i in nums){ console .log (nums[i]); } for (let nhj of nums){ console .log (nhj); }
示例作业
<pre> 1 、给页面中的所有按钮绑定点击事件,当点击这些按钮时弹出“这个页面的第几个按钮”。 2 、分别定义无参无返回,有参无返回,无参有返回和有参有返回的箭头函数,并且调用它。 3 、定义三个变量snum,name,classroom三个变量,通过解构将这三个变量合并成一个对象。 4 、var dog = {n :"旺财" ,weight :2 ,color :"黑色" };通过解构取出旺财的所有属性值。 5 、定义一个学生对象,包含一个eat方法,通过解构取出这个方法并调用它。 6 、定义一个没有参数个数限制的函数,打印出输入的参数个数。 </pre> <button > 按钮1</button > <button > 按钮2</button > <button > 按钮3</button > <script > var cf=document .querySelectorAll ("button" ); for (let i=1 ;i<=cf.length ;i++){ cf[i-1 ].onclick =()=> alert ("第" +i+"个" ) } let fn1 =( )=>console .log ("无参数无返回值" ); let fn11 =( )=>{ console .log ("无参数无返回值" ) } fn1 (); let fn2 =name=>console .log ("有参数无返回值:" +name); fn2 ("张三" ); let fn3 =(name,age )=>console .log ("有参数无返回值:" +name+" " +age); fn3 ("散" ,12 ); let fn4 =( )=>45 ; console .log ("无参数有返回值:" +fn4 ()); let fn5 =(a,b )=>a+b; console .log ("有参数有返回值:" +fn5 (5 ,1 )) let snum=40 ; let name="C1901" ; let classroom="1班" ; let classinfo={snum,name,classroom}; console .log (classinfo); var dog={ n :"旺财" , weight :2 , color :"黑色" } let {n,weight,color}=dog; console .log (n,weight,color); let {n :a,weight :b,color :c}=dog; console .log (a,b,c); let student={ eat :(food )=> console .log ("吃" +food) } let {eat}=student; eat ("西瓜" ); let num6 =(...arr )=>console .log (arr.length ); num6 (1 ,5 ,6 ,7 ) </script >
Map 创建map 放入值 map.set ("st01" ,"张三" ); map.set ("st02" ,"李四" ); map.set ("st03" ,"王五" ); map.set ("st01" ,"vm" ); console .log (map);
得到长度 console .log ("map的长度:" +map.size );
取值 console .log (map.get ("st01" ));
for of取值 for (let [key,value] of map){ console .log (key,value); }
foreach循环 map.forEach ((value,key ) => { console .log (key,value); });
key是对象 let hm=new Map (); let js={}; let tm={name :"提莫" ,age :19 }; hm.set (js,"这是个空值" ); hm.set (tm,"这是temo对象" ); console .log (hm.get (js)); console .log (hm.get (tm));
map变数组 let arr=Array .from (map); console .log (arr); console .log (arr[2 ][1 ]);
map合并 let a=new Map ([['st1' ,'张三' ],['st2' ,'李四' ],['st3' ,'王五' ]]);let b=new Map ([['num1' ,'香蕉' ],['num2' ,'苹果' ],['num3' ,'葡萄' ]]); console .log (a); console .log (b); var merge=new Map ([...a,...b]); console .log (merge);
Set 添加值 let set=new Set (); set.add ("提莫" ); set.add ("德玛" ); set.add ("剑圣" );
for of取值 for (let hj of set){ console .log (hj); }
数组变set let arrs=[1 ,4 ,6 ,8 ]; let set1=new Set (arrs); console .log (set1);
set变数组 set1.add ("k" ); set1.add ("L" ); let arrs2=[...set1];console .log (arrs2);
合并 交集 差集 let hight=new Set (['张三' ,'李四' ,'王五' ,'刘均' ,'刘贺' ]); let mi=new Set (['张三' ,'谢军' ,'王五' ]); let mergeset=new Set ([...hight,...mi]); console .log (mergeset); let intersection=new Set ([...hight].filter (x => mi.has (x))); console .log (intersection); let jk=new Set ([...hight].filter (x => !mi.has (x))); console .log (jk);
ES6类 class Student { constructor (name,age ){ this .name =name; this .age =age; console .log ("student构造方法运行!" ); } get name (){ console .log ("正在取值!" ); return this .newname ; } set name (val ){ console .log ("正在设置值!" ); this .newname =val; } sayhi ( ){ console .log ("你好:" +this .name ); console .log ("年龄:" +this .age ) } static sa ( ){ console .log ("名字:" +this .name ); console .log ("age:" +this .age ); } } let zs=new Student ("张三" ,19 ); zs.sayhi (); console .log (zs.name ); Student .sa (); class Teach extends Student { constructor (name,age ){ console .log ("老师的构造方法!" ); super (name,age); } } let lis=new Teach ("李四" ,19 ); console .log (lis.age ); console .log (lis.name );
模板字符串 let mona='temo' ;let age =16 ;let t=` <div> <h3>名字=${mona} </h3> <p>年龄=${age} </p> </div> ` ;document .body .innerHTML =t;console .log (t);function f ( ){ return "你好" ; } let t2=`game start ${f()} ` ;console .log (t2);
Promise task1 ().then (function (su ){ console .log ("Task1服务器返回成功:" +su); }).catch (function (da ) { console .log ("抓取异常...." +da); }).finally (function ( ){ console .log ("收尾工作" ); })
单个使用 function task1 ( ){ let t1=new Promise (function (su,er ){ let h=Math .random (); if (h>=0.5 ){ su ("成功!" ); }else { er ("失败!" ); } }) return t1; } let tk1=task1 (); tk1.then (function (su ){ console .log (su); },function (er ){ console .log (er); })
链式 function jok ( ){ let p2=new Promise (function (su,er ){ $.ajax ({ url :'https://autumnfish.cn/api/joke/list?num=3' , type :'get' , success :function (da ){ su (da); }, error :function (msg ){ er (msg) } }) }) return p2; } function music ( ){ let p3=new Promise (function (su,er ){ $.ajax ({ url :'https://api.uomg.com/api/rand.music?sort=%E7%83%AD%E6%AD%8C%E6%A6%9C&format=json' , type :'get' , success :function (da ){ su (da.data ); }, error :function (msg ){ er (msg) } }) }) return p3; } $("#ls" ).on ('click' ,function ( ){ let hj=jok (); hj.then (function (su ){ console .log (su.jokes ); return music (); }).then (function (da ){ console .log (da); }) })
all function ts1 ( ){ let p4=new Promise (function (su,er ){ setTimeout (function ( ){ su ("下单成功!" ); },2000 ) }) return p4; } function ts2 ( ){ let p5=new Promise (function (su,er ){ setTimeout (function ( ){ su ("支付成功!" ); },1000 ) }) return p5; } function ts3 ( ){ let p6=new Promise (function (su,er ){ setTimeout (function ( ){ su ("订单修改成功!" ); },3000 ) }) return p6; } Promise .all ([ts1 (),ts2 (),ts3 ()]).then (function (res ){ console .log ("111:" +res); })
race function ts1 ( ){ let p4=new Promise (function (su,er ){ setTimeout (function ( ){ su ("下单成功!" ); },2000 ) }) return p4; } function ts2 ( ){ let p5=new Promise (function (su,er ){ setTimeout (function ( ){ su ("支付成功!" ); },1000 ) }) return p5; } function ts3 ( ){ let p6=new Promise (function (su,er ){ setTimeout (function ( ){ su ("订单修改成功!" ); },3000 ) }) return p6; } Promise .race ([ts1 (),ts2 (),ts3 ()]).then (function (rs ){ console .log ("116:" +rs); })
练习 <script> function task1 ( ) { let p1 = new Promise (function (su, er ) { console .log ("采蘑菇!" ); su ("采蘑菇" ); }); return p1; } function task2 ( ) { let p2 = new Promise (function (su, er ) { console .log ("杀鸡!" ); su ("杀鸡" ); }); return p2; } Promise .all ([task1 (), task2 ()]).then (function (res ) { console .log ("升级成功!" ); }); function task3 ( ) { let p3 = new Promise (function (su, er ) { setTimeout (function ( ) { su ("采蘑菇" ); }, 2000 ); }); return p3; } function task4 ( ) { let p4 = new Promise (function (su, er ) { setTimeout (function ( ) { su ("杀鸡" ); }, 1000 ); }); return p4; } Promise .race ([task3 (), task4 ()]).then (function (res ) { console .log ("恭喜 " + res + " " + "获得大陆勇士的称号" ); }); let dilef1 = 0 ; function div1 ( ) { let p5 = new Promise (function (su, er ) { let s1 = setInterval (function ( ) { var cf1 = document .querySelector ("#d1" ); let num1 = Math .ceil (Math .random () * 20 ); dilef1 = dilef1 + num1; cf1.style .left = dilef1 + "px" ; if (dilef1 >= 1446 ) { clearInterval (s1); su ("1" ); } }, 1000 ); }); return p5; } let dilef2 = 0 ; function div2 ( ) { let p5 = new Promise (function (su, er ) { let s2 = setInterval (function ( ) { var cf2 = document .querySelector ("#d2" ); let num2 = Math .ceil (Math .random () * 20 ); dilef2 = dilef2 + num2; cf2.style .left = dilef2 + "px" ; if (dilef2 >= 1446 ) { clearInterval (s2); su ("2" ); } }, 1000 ); }); return p5; } let dilef3 = 0 ; function div3 ( ) { let p5 = new Promise (function (su, er ) { let s3 = setInterval (function ( ) { var cf3 = document .querySelector ("#d3" ); let num3 = Math .ceil (Math .random () * 20 ); dilef3 = dilef3 + num3; cf3.style .left = dilef3 + "px" ; if (dilef3 >= 1446 ) { clearInterval (s3); su ("3" ); } }, 1000 ); }); return p5; } Promise .race ([div1 (), div2 (), div3 ()]).then (function (res ) { console .log ("149:第" + res + "个div获得了冠军" ); }); </script>
ES7 Promise简化 //async 关键字返回的是 promise对象 function task1() { return new Promise((su, er) => { //模仿ajax setTimeout(function () { su("task1!"); }, 2000); }); } function task2() { return new Promise(function (su, er) { setTimeout(function () { su("task2!"); }, 1000); }); } async function task3() { return "hj"; } let ft = task1(); console.log(ft); //ES6 task1().then(function (da) { console.log(da); }); task1().then((da) => console.log(da)); // 有async 的函数 才可以使用 await async function test() { //await 等待 返回的是结果 let ps = await task1(); console.log("44:" + ps); let ps2 = await task2(); console.log("46:" + ps2); let ps3 = await task3(); console.log("52:" + ps3); } test();
some查看数组是否满足条件 var a=[ {id :1 ,name :'张三' }, {id :2 ,name :'李四' }, {id :4 ,name :'王五' } ]; a.some ((item )=> { if (item.id ==2 ){ item.name ="李思2" } }) console .log (a);
findindex查找下标 var inde=a.findIndex ((index )=> { if (index.id ==2 ){ return index } }) console .log (inde);
filter 满足条件 var nr= a.filter ((index )=> { if (index.id ==2 ){ return index; } }) console .log (nr);
find 满足条件 var finsall= a.find ((index )=> { if (index.id ==2 ){ return index; } }) console .log (finsall);
splice添加 var hj={id :5 ,name :"例外" }a.splice (1 ,0 ,hj); console .log (a);
splice删除 内容复制到剪切板 const copyToClipboard = (text ) => navigator.clipboard .writeText (text);copyToClipboard ("Hello World" );
查找日期位于一年的第几天 const dayOfYear = (date ) =>Math .floor ((date - new Date (date.getFullYear (), 0 , 0 )) / 1000 / 60 / 60 / 24 );var log=dayOfYear (new Date ());console .log (log);
计算2个日期相差多少天 const dayDif = (date1, date2 ) => Math .ceil (Math .abs (date1.getTime () - date2.getTime ()) / 86400000 )dayDif (new Date ("2020-10-21" ), new Date ("2021-10-22" ))
随机生成16进制颜色 const randomHex = ( ) => `#${Math .floor(Math .random() * 0xffffff ).toString(16 ).padEnd(6 , "0" )} ` ;console .log (randomHex ());
检验数组奇偶 const isEven = num => num % 2 === 0 ;
求数字的平均值 const average = (...args ) => args.reduce ((a, b ) => a + b) / args.length ;average (1 , 2 , 3 , 4 );
回到顶部 const goToTop = ( ) => window .scrollTo (0 , 0 ); goToTop ();
JS排序对象数组 var cf=[ {"name" :'张三' ,"result" :98 }, {"name" :'张三2' ,"result" :10 }, {"name" :'张三3' ,"result" :20 }, {"name" :'张三4' ,"result" :30 }, {"name" :'张三5' ,"result" :40 }, {"name" :'张三6' ,"result" :60 }, {"name" :'张三7' ,"result" :70 }, {"name" :'张三8' ,"result" :80 }, {"name" :'张三9' ,"result" :90 }, {"name" :'张三10' ,"result" :100 }, {"name" :'张三11' ,"result" :75 }, {"name" :'张三12' ,"result" :65 }, {"name" :'张三13' ,"result" :74 }, {"name" :'张三14' ,"result" :78 }, {"name" :'张三15' ,"result" :99 }, ] function sortData (a, b ) { return b.result - a.result } cf.sort (sortData);