JavaScript代码笔记


Javascript

使用js的三个方式

内嵌js、script代码块、外部引用js


<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Titletitle>
   <script type="text/javascript">
       alert('head hello')
   script>
   <script src="1.js" type="text/javascript">script>
head>
<body onload="alert('hello')">
?
body>
html>

注释

双斜杠 // 或 /* 与 */ 之间的代码被视为注释

输出

  • alert()

  • document.write()

    在 HTML 文档完全加载后使用 document.write()删除所有已有的 HTML


    <html>
    <body>
    ?
    <h1>我的第一张网页h1>
    ?
    <p>我的第一个段落p>
    ?
    <button onclick="document.write(5 + 6)">试一试button>
    ?
    body>
    html>
  • innerHTML()

  • console.log()

变量

JavaScript 变量是存储数据值的容器。

let age = 1; let departmentName = "Program";

错误:let dn = "sale"; let n1 = "sale"; let 1n = "sale";

可以包含英文字母+数字+下划线+$,不能以数字开头,建议以英文字母开头。

不要用拼音命名变量,不要用生僻的英文单词命名

let定义是局部变量,范围是以大括号为界。var局部变量,和let一样,区别是有变量提升现象。

<script>
   function f() {
       let age = 1;
       console.log('age=' + age)
  }
?
   //报错
   // console.log('age=' + age)
?
   f();
?
   function f1() {
       var username = 'zhangshan';
       console.log('name=' + username);
  }
?
   f1();
   //alt+shift+down
   //报错
   // console.log('name=' + username);
</script>
//报错
/*console.log('age=' + age);
let age = 1;*/
//var的提升现象
console.log('age=' + age);
var age = 1;
const MONEY = 10000;
//常量的值不能改变报错
// alert(MONEY++);

数据类型

原始数据

  • string

  • number

  • boolean

  • undefined

复杂数据

  • function

  • object

数组(在 JavaScript 中数组属于对象)

Undefined:没有值的变量,其值是 undefined。typeof 也返回 undefined。

Null : object

布尔类型Boolean:boolean

数值类型Number:number

字符串String:string

对象:object

函数:function

Undefined 与 Null 的区别

  • Undefined 与 null 的值相等,但类型不相等:

  • typeof, JS中if判断时,null和undefined为false ,数字0也是false

通过指定表示未找到相应元素时也是false if(document.getElementById('xx')){}

<script>
   let age = 1;
   let username = "admin";
   let adult = true;
   let money = null;
   let girlFriend;
   document.write('age: ' + typeof age + "     ;");
   document.write('username: ' + typeof username + "     ;");
   document.write('brithday: ' + typeof brithday + "     ;");
   document.write('money: ' + typeof money + "     ;");
   document.write('girlFriend: ' + typeof girlFriend + "     ;");
   //age: number username: string brithday: object money: object girlFriend: undefined
</script>

if条件判断时,true 、1是真可以执行if语句块内的代码

null、undefined、0、-1再条件判断里是假的

<script>
   let adult = true
   if (adult) {
       document.write("true");
  } else {
       document.write("false")
  }
   let money = null;
   //JS中把空当成false
   if (money) {
       document.write("1000$");
  } else {
       document.write("10000000$")
  }
   let girlFriend;
   if (girlFriend) {//undefined 也是false
       document.write("有女朋友");
  } else {
       document.write("没有")
  }
?
   let age = 0;
   if (age) {//0,-1也是false 1的时候为true
       document.write("ok");
  } else {
       document.write("no ok")
  }
</script>

双等和三等的判断

<script>
   let age = 1;
   if (age == 1) {
       alert("age is Number 1 ");//ok
  }
   if (age == "1") {
       alert("age is string '1' ");//ok
  }
   //=== 不仅内容要相等,类型也要相等
   if (age === "1") {
       alert("equals");
  } else {
       alert("no equals")
  }
</script>

总结:

  • 基本数据类型(Number,Boolean,String ,Null,undefined)

  • typeof运算符判断类型

  • if判断对于数字0,,-1,null, undefined,返回内容任一项不等返回false

isNaN()函数:是数字返回false,不是数字返回true

  • infinite是一个数字

  • age = "1";//他是一个字符串也是一个数字

<script>
   // alert(1/0);//infinity
   // alert(typeof Infinity);//类型number
   // is not a number() 函数 isNaN()
   let age = 1;
  /* alert(isNaN(age));//false
  age = "1";//他是一个字符串也是一个数字
  alert(isNaN(age))//false
  age = "a";
  alert(isNaN(age));//true*/
   age = Infinity;//是一个数字
   alert(isNaN(age));//false
</script>

number的一些方法

  • parseInt,parseFloat,toFixed

Number

math

document.write(Math.ceil(1.1));//向上取整为2
document.write(Math.ceil(-1.1));//向上取整-1 可以理解为ceil是向大数取整
document.write(Math.floor(1.1));//1
document.write(Math.floor(-1.1));//-2 floor可以理解为向小数取整
document.write(Math.trunc(-1.1));//trunc表示截断,断开小数点之后的数
//正数的四舍五入是正常的 负数的四舍五入是-0.6近-1,-0.5近0
document.write(Math.round(-0.5));
document.write(Math.round(-0.6));
document.write(Math.round(1.4));
document.write(Math.round(1.5));

String字符串

面试题:substr(起始位置,长度)和substring(起始位置,结束位置)的区别

substr()和substring()都可以进行字符串的截取

substr(起始位置,长度)

substring(起始位置,结束位置):不包括结束索引

闭包(面试点)

函数中的函数(在一个函数中定义另一个函数,后者在前者内部)

闭包就是能够读取其他函数内部变量的函数。例如在javascript中,只有函数内部的子函数才能读取局部变量所以闭包可以理解成“定义在一个函数内部的函数。

在本质上,闭包是将函数内部和函数外部连接起来的桥梁。

优点:解决了一个问题,函数外部读取函数内部局部变量

缺点:1. 闭包所在的外部函数执行完后,它的局部变量无法自动回收,会带来内存泄漏(IE),占用大量内存无法释放。2. 闭包可以改变外部函数的局部变量,使用时需要注意

// 闭包就是能够读取其他函数内部变量的函数。
function fout() {
//局部变量
let count = 0;
//下面的函数是闭包,局部函数的外部调用
return function fin() {
alert(++count);
}
}
//fn指向了fout内部的函数
let fn = fout();
fn();//1
fn();//2
fn();//3

prototype

多用于方法,资源优化,使得每个对象不会占用太多的内存资源

函数(作为普通函数,类)

JavaScript 函数是被设计为执行特定任务的代码块。

函数调用

函数中的代码将在其他代码调用该函数时执行:

  • 当事件发生时(当用户点击按钮时)

  • 当 JavaScript 代码调用时

  • 自动的(自调用)

function f(){},switch语句

function f(num1, num2,opt) {
switch (opt) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return num1 + num2;
}
}
//函数传参
let num = f(1, 2,'*');
console.log(num);
num = f(1, 0,'/');
console.log(num);//鹰飞你提

函数当作类来使用

function f(num1, num2,opt) {
//this是当前调用本函数的对象。
console.log('this=' + this);
switch (opt) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return num1 + num2;
}
}
//函数传参
let num = f(1, 2,'*');
console.log(num);
num = f(1, 0,'/');
console.log(num);//鹰飞你提

//定义一个类 Java:class
function Calc(brand,manufacturers) {
//类内部,this指向了对象
this.brand = brand;
this.manufacturers = manufacturers;
this.work = f;
}

//创建出一个对象,calc这个变量就指向了这个对象
let calc = new Calc('suandekuai', 'Huawei');
console.log(calc.brand);
console.log(calc.manufacturers);
let result = calc.work(1, 2, '-');
console.log(result);

定义一个苹果类

定义一个类:人

局部变量全局变量

  • 通过 var 关键词定义的全局变量属于 window 对象

  • 通过 let 关键词定义的全局变量不属于 window 对象

//全局变量
let name = "globalName";
let age = 100;
function f() {
let name = "localName";
//局部变量
console.log(name);
console.log(age);
}
f();
console.log(name);

引用类型

数组

存储一组数组,通过连续的下标来访问数组元素,下标(索引)从0开始,数组的长度不固定,数组的数据类型不固定。

数组的初始化

  • [x,x,x]

  • new Array()

  • string.split

let arr = [1, 2, 3];
console.log(arr.length)
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
arr[0] = 'a';
arr[1] = new Date();
console.log('改变值后的0下标数组='+arr[0]);
console.log('改变值后的1下标数组='+arr[1]);

for (let i = 0; i < arr.length; i++) {
console.log('循环输出数组'+arr[i]);
}

pop()后弹、push()后加

let arr = new Array();
console.log(arr.length);//数组默认长度是0
for (let i = 0; i < 5; i++) {
arr[i] = i;//直接复制
}
console.log('赋值后=' + arr.length);
let item = arr.pop();
console.log('dot pop= ' + arr.length);//弹出数据后数组长度变短
console.log(arr)

arr.push(4);
console.log(arr);

shift()前弹unshift()前加一个数组和join()

//往数组里面加一个分割符生成字符串
let str = arr.join();
console.log(str);
str = arr.join('-');//生成一个以‘-’为分隔符的数组字符串
console.log(str);
//前弹一个数组元素
item = arr.shift();
console.log('item = ' + item);
console.log('arr = ' + arr);
arr.unshift(0);
console.log(arr)

切片访问数组slice

console.log('arr = ' + arr.slice(1, 3));

数组排序

arr = arr.sort();
console.log('arr顺序排序后(从小到大) = ' + arr);
arr = arr.reverse();
console.log('arr倒序排列后(从大到小) = ' + arr);

对象

可以通过new类创建对象

//构造器定义一个类 Java:class
function Calc(brand,manufacturers) {
//类内部,this指向了对象
this.brand = brand;
this.manufacturers = manufacturers;
}

//创建出一个对象,calc这个变量就指向了这个对象
let calc = new Calc('suandekuai', 'Huawei');
console.log(calc.brand);
console.log(calc.manufacturers);

JSON对象

  • JSON 对象被花括号 {} 包围。

  • JSON 对象以键/值对书写。

  • 键必须是字符串,值必须是有效的 JSON 数据类型(字符串、数字、对象、数组、布尔或 null)。

  • 键和值由冒号分隔。

  • 每个键/值对由逗号分隔。

//键值对的方式定义属性和方法
let person = {
firstName: 'zhang',
lastName: 'san',
fullName: function () {
return this.firstName + this.lastName;
}
}
let fullName = person.fullName();
console.log(fullName);

日期

new XX(),XX()就是构造函数 ,new Date(),Date()就是构造函数,是一个无参的。

this是什么?

JavaScript this 关键词指的是它所属的对象。

它拥有不同的值,具体取决于它的使用位置:

  • 在方法中,this 指的是所有者对象。

  • 单独的情况下,this 指的是全局对象。

  • 在函数中,this 指的是全局对象。

  • 在函数中,严格模式下,this 是 undefined。

  • 在事件中,this 指的是接收事件的元素。

像 call() 和 apply() 这样的方法可以将 this 引用到任何对象。

//this是当前调用本函数的对象。
console.log('this=' + this);

call()方法的使用

apply()方法的使用

let person = {
fullName: function () {
return this.firstName + this.lastName;
},
fullName2: function (firstName,lastName) {
return firstName + lastName;
}
}
let p1 = {
firstName: '赵',
lastName: '一'
}
//apply和call区别在于apply第二个参数是Array,而call是将一个个传入
fullName = person.fullName.apply(p1);
console.log(fullName);
fullName = person.fullName2.apply(p1, ['钱', '二']);
console.log(fullName);

math()函数,和call、apply方法的调用

//正常的max方法
let max = Math.max(6, 2, 100, 3)
console.log(max);

//使用call调用max方法
max = Math.max.call(null, 6, 22, 1, 3);
console.log(max);

//使用apply方法
let arr = [66, 2, 1, 3];
max = Math.max.apply(null, arr);
console.log(max);

JSON

JSON对象,JSON字符串

页面向后台传递数据JSON有两种格式,一种是JSON字符串,把JSON对象通过JSON.stringify()传递,原因是取决于后台只能识别JSON字符串。

如果后台只能识别JSON对象,页面需要传递JSON对象。

后台返回给页面一个JSON字符串(只能是字符串,后台技术规定的),页面拿到JSON字符串后台不好处理,JSON.parse()转换成对象就可以通过对象.XX来获取数据

DOM

Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问。

document object model 文档对象模型,浏览器会把HTML文档当作一个对象,放在程序中进行处理。document

通过document可以获取页面上元素的值或属性等,可以动态增加页面上的元素或移除元素,可以给元素动态赋值,可以改变元素的外观。

function checkAll(elem) {
// xx.checked表示复选框是否被选中了,选中返回true,否则false
// alert(elem.checked)
let cbxSons = document.getElementsByName("cbxSon");
for (let i = 0; i < cbxSons.length; i++) {
// 所有复选框的选择状态和全选的复选框保持一致
cbxSons[i].checked = elem.checked;// 将true或false赋值给所有的
}
}

动态添加下拉列表





Title




下拉框的值:
下拉框显示:




选择器

获取页面元素可以用指定的标识入:id , class, name , tagName等

function init() {
// JavaScript代码先执行,后面HTML代码后执行
let div1 = document.getElementById("div1");
console.log(div1);

// 根据classname获取,获取的是数组
let c1 = document.getElementsByClassName("c1");
console.log(c1);
for (let i = 0; i < c1.length; i++) {
console.log(c1[i]);
}
// 根据标签名获取,获取的是数组
let divs = document.getElementsByTagName("div");
for (let i = 0; i < divs.length; i++) {
console.log(divs[i]);
}
}

事件

单击,双击,鼠标在

DOM和事件紧密联系。所有的事件以on开头,如:onclick单击

dbclick,change,blur,focus,mouse(),keyboard()





Title



onmouseover="mouseover();" onmouseout="mouseout();">

1







Title





计算器

step1

做边框

step2

做外观





Title




0























step3

做交互





Title





0


























对话





Title











正则

==书写逻辑==第一步我要写什么第二步我能写几个

保证数据有效性:非空,格式正确

表达式: let reg = /xxx/; reg.test(待检查的内容) true/false





Title






替换和正则的参数

let reg = /^[\u4e00-\u9fa5]{2,4}$/;
console.log(reg.test(""));

// g Global/ i Ignore
reg = /0/g;
// i 可以表示忽略大小写
// g 表示全局替换
console.log("a01234567890A".replace(reg, "零").replace(/a/ig,"b"));

转义字符\d, \D, \s, \S

// \d表示数字
reg = /^\d$/;
console.log(reg.test(1));
console.log(reg.test('a'));
// \D表示非数字
reg = /^\D$/;
console.log(reg.test(1));
console.log(reg.test('a'));
// \s表示空格
reg = /^\s+$/;
console.log(reg.test(" "));
console.log(reg.test(' '));
// \S表示非空格
reg = /^\S$/
console.log(reg.test(" "));
console.log(reg.test(' '));

\W ,\w

// \w表示:字母、数字、下划线
reg = /^\w+$/;
console.log(reg.test('abcABC123_'));//true
console.log(/^[a-zA-Z0-9_]+$/.test('abcABC123_'));// true
console.log(reg.test('abc中.'));// false
1
// \W非字母表示:除了字母数字下划线
reg = /^\W+$/;
console.log(reg.test('abcABC123_'));// false
console.log(reg.test('中'));// true

// /^\w\W+$/ 表示一切 和 /^.+$/差不多
reg = /^[\w\W]+$/;
console.log(reg.test("中华。 @#%、 。"));//true
console.log(/^.+$/.test("中华。 @#%、 。"));//true

数据有效性,表单校验,失去焦点校验


<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Titletitle>
   <style>
       input {
           border: 1px solid lightblue;
      }
   style>
   <script>
       // 定义正则来对input文本框输入内容校验
       // 定义正则只能输入字母、数字、下划线、4-8位
       let regUserName = /^\w{4,8}$/;
       let regPassword = /^\w{4,8}$/;
?
       //页面加载完成后执行
       window.onload = function () {
           // 1.通过name查找
           // let username = document.getElementsByName("username")[0];
           // 2.通过HTML元素查找 ,原理是该元素位于HTML里面的第几位
           let username = document.forms[1].username;
           let password = document.forms[1].password;//form[1].可以点id,点name,如果name值相同,采用数组访问
           // 3.通过HTML元素的name查找,[]内可以放id name属性查找
           // let username = document.forms["frm"].username;
           username.onblur = function () {
               check(username, regUserName);
          }
           // 绑定事件的监听 参数:事件类型,事件方法,。。。
           password.addEventListener('blur',function () {
               check(password, regPassword);
          },true)
           // 给表单绑定提交事件
           /*document.forms[1].onsubmit = function () {
              let resultUsername, resultPassword;
              resultUsername = check(document.forms[1].username, regUserName);
              resultPassword = check(document.forms[1].password, regPassword);
              // 若有一个为false则提交不成功
              return resultPassword && resultUsername;
          }*/
      };
?
       // 第二种页面调用js方式,通过HTML内嵌事件调用
       function fromSubmit() {
           let resultUsername, resultPassword;
           resultUsername = check(document.forms[1].username, regUserName);
           resultPassword = check(document.forms[1].password, regPassword);
           // 若有一个为false则提交不成功
           return resultPassword && resultUsername;
      }
?
       // 公共检查方法,谁都可以调用
       function check(element,regExp) {
           if (regExp.test(element.value)) {
               element.style.borderColor = 'lightblue';
               return true;
          } else {
               element.style.borderColor = 'red';
               return false;
          }
      };
   script>
head>
<body>

   <form action="" method="post" name="frm">
       <label>用户名:label>
       <input type="text" name="username">
       <label>密码:label>
       <input type="password" name="password">
       <input type="submit">
   form>

   <form action="https://www.baidu.com" method="post" name="frm"  onsubmit="return fromSubmit()">
       <label>用户名:label>
       <input type="text" name="username">
       <label>密码:label>
       <input type="password" name="password">
       <input type="submit" value="提交">
   form>
body>
html>

BOM


<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Titletitle>
   <script>
       console.log(window);
       window.onload = function () {
           document.getElementsByTagName("button")[0].onclick = function () {
               //location的相关属性
               let hostname = Location.hostname;
               let protocol = location.protocol;
               let path = location.pathname;
               let prot = location.port;
               alert(protocol + '//' + hostname +':'+ prot + path);
               //指定浏览器地址,并且触发刷新的动作
               window.location.href = '3.html';
          }
      }
   script>
head>
<body>
   <button>3.htmlbutton>
   <button type="button" onclick="history.forward()">前进button>
body>
html>

轮播


<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Titletitle>
   <style>
       .lamp {
           width: 50px;
           height: 50px;
           border: 1px solid lightblue;
           float: left;
           border-radius: 50%;
      }
       #clear {
           clear: both;
      }
   style>
   <script>
       // 灯定时器
       let timerLamp;
       // 灯序号
       let indexLamp = 0;
       // 所有的灯
       let lamps;
?
       window.onload = function () {
           let btnStop = document.getElementById("btnStop");
           let btnStart = document.getElementById("btnStart");
           btnStop.disabled = true;
           btnStart.onclick = function () {
               this.disabled = true;
               btnStop.disabled = false;
               timerLamp = window.setInterval(lampShow, 1000);
          };
           btnStop.onclick = function () {
               this.disabled = true;
               btnStart.disabled = false;
               // 让定时器失效
               window.clearInterval(timerLamp);
          };
           // 初始化灯
           lamps = document.getElementsByClassName('lamp');
      }
?
       function lampShow() {
           // 所有的灯灭灯
           for (let i = 0; i < lamps.length; i++) {
               lamps[i].style.backgroundColor = 'white';
          }
           // 让灯亮起来
           lamps[indexLamp++].style.backgroundColor = 'red';
           /*if (indexLamp == 6) {
              indexLamp = 0;
          }*/
           // 数字零的滚动
           indexLamp %= 6;
      }
?
   script>
head>
<body>
   <div class="lamp">div>
   <div class="lamp">div>
   <div class="lamp">div>
   <div class="lamp">div>
   <div class="lamp">div>
   <div class="lamp">div>
   <div id="clear">div>
   <div>
       <button id="btnStart" type="button">startbutton>
       <button id="btnStop" type="button">stopbutton>
   div>
body>
html>