首页 > 基础资料 博客日记

JavaScript 详解——Vue基础

2024-09-10 16:00:08基础资料围观28

Java资料网推荐JavaScript 详解——Vue基础这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

第一章  JavaScript简介

为什么学习javascript ?


JavaScript 是全球最流行的编程语言。

JavaScript 是属于 Web 的编程语言。

JavaScript 是 web 开发者必学的三种语言之一:

HTML 定义网页的内容
CSS 规定网页的布局
JavaScript 对网页行为进行编程
    
       

javascript的作用

JavaScript 能够改变 HTML 内容

JavaScript 能够改变 HTML 属性

JavaScript 能够改变 HTML 样式

JavaScript 能够隐藏 HTML 元素

JavaScript 能够显示 HTML 元素     

javascript  的使用

    1、在 HTML/Vue 中,JavaScript 代码必须位于起始和结束script 标签之间。
    1️⃣script标签可以嵌入到html中,不推荐
    2️⃣常用的是外部脚本:分离了 HTML 和代码;使 HTML 和 JavaScript 更易于阅读和维护
     已缓存的 JavaScript 文件可加速页面加载

<template>
  <div class ="onePage">
    <h1>Vue——JS 简介</h1>
    <h3 id="demo">hello</h3>
    <el-button type="primary" @click="changeContent">点击我看js改变Html内容</el-button>
    <br><br>
    <img id="myImage" src="/images/hm3A.png"><br><br>
    <el-button type="primary" @click="changeClass">能够改变 HTML 属性</el-button>
    <br><br>
    <el-button type="primary" @click="changeStyle">能够改变 HTML 样式</el-button>
    <br><br>
    <el-button type="primary" @click="changeHide">能够隐藏 HTML 属性</el-button>
    <br><br>
    <el-button type="primary" @click="changeShow">能够显示 HTML 属性</el-button>
    <br><br>


  </div>
</template>

<script>
export default {
  name: "onePage",
  components: {},
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  methods: {
    // JavaScript 能够改变 HTML 内容
    changeContent() {
      document.getElementById("demo").innerHTML = "Hello JavaScript!";
    },
    changeClass() {
      document.getElementById("myImage").src = "/images/hmjt.png";
    },
    changeStyle() {
      document.getElementById("demo").style.fontSize = "50px";
    },
    changeHide() {
      document.getElementById("demo").style.display = "none";
    },
    changeShow() {
      document.getElementById("demo").style.display = "block";
    }
  }
}

</script>

<style scoped>

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 80vw;
  /*字体*/
  font-size: 25px;
}

.container {
  display: flex;
  justify-content: center;
}

#myImage {
  width: 100px;
  height: 100px;
}
</style>

第二章  JS语句、标识符

JS语句

1️⃣javascript 程序单位是行,也就是一行一行执行,一般一行就是有个语句

2️⃣语句以分号结束,有个分号就表示有个语句结束,可以不加

标识符

1️⃣标识符指的是用来识别各种值的合法名称,最常见的标识符就是变量名

2️⃣标识符由字母、$、_、数字组成,不能以数字开头,不能使用保留字

保留字包含
break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,false

finally,for,function, if,import,in,instanceof,new,null,return,super,switch,this,throw,true,try,

typeof,var,void,while,with,yield,implements,interface,let,package,private,protected,public,、static等,用到查

代码


<template>
  <div class="div1">
    <h1>第二章 JS语句、标识符</h1>
  </div>
</template>
<script>
export default {
  name: 'twoPage',
  data() {
    return {
      number: 1,
    }
  },
  mounted() {
    this.One();
  },
  methods: {
    One(){
// javascript 程序单位是行,也就是一行一行执行,一般一行就是有个语句
// 语句以分号结束,有个分号就表示有个语句结束,可以不加
      var one1=10;
      console.log(one1);
//标识符
//标识符指的是用来识别各种值的合法名称,最常见的标识符就是变量名
//标识符由字母、$、_、数字组成,不能以数字开头,不能使用保留字
      var userName = "张三";
      let aa=1;
      console.log(aa);
      aa=3;
      const ba=2;
      console.log(ba);

      var user_name = "李四";
      var $userName = "王五";
      var _userName = "赵六";
      var $_userName = "钱七";
      var user_name1 = "孙八";
      // var 1userName=1;
      // var break=1;

      console.log(userName);
      console.log(user_name);
      console.log($userName);
      console.log(_userName);
      console.log($_userName);
      console.log(user_name1);

    }
  }
}
</script>
<style scoped>
</style>

变量

变量声明和赋值

声明变量由两部分组成: 关键字 变量名;

变量赋值:变量名=值数据;

声明并赋值:关键字 变量名=值数据;

//声明
let a;
//赋值
a=1;
//声明并赋值
let b = 1;

变量提升概念:

先解析代码,获取所有被声明的变量,然后再一行一行的运行,这造成的结果就是所有变量的声明语句都会被提升到代码的头部,这就被叫做变量提升

 //变量提升
    console.log("x", x);//这样会是什么结果呢?  undefind
    var x = 10;
    //实际上运行步骤是
    // var x;
    // console.log("x",x);
    // x = 10;

let和var区别

都是js的关键字

let声明的变量注意事项:

不允许重复声明,

只能在块级作用域使用,

不存在变量提升,必须声明变量后才能使用,不然报错Uncaught ReferenceError错误

js中内置的一些关键字不能被当做变量名

var声明的变量注意事项:

允许重复声明

可以在任意地方使用

可以在声明语句前使用-变量提升

大部分情况使用let和var区别不大,但是let比var更严谨,所以推荐使用let

总结:

不声明使用,程序报错

不赋值使用:undefined

不声明直接赋值:js允许,会变为全局变量,不提倡

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>变量</title>
</head>
<body class="one">

<script>
    //声明(定义)变量有两部分组成:关键字  变量名
    //关键字var,创建变量a
    let a = 1;
    console.log("a", a);
    //重新赋值
    a = 2;
    console.log("a", a);
    //可以在一条语句中声明许多变量,以 var 作为语句的开头,并以逗号分隔变量:
    //可跨多行
    let person = "Bill Gates", carName = "porsche", price = 15000;
    console.log("person", person);
    console.log("carName", carName);
    console.log("price", price);

    //undefined
    let car;
    console.log(car);

    //变量提升
    console.log("x", x);//这样会是什么结果呢?
    var x = 10;
    //实际上运行步骤是
    // var x;
    // console.log("x",x);
    // x = 10;
</script>
</body>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</html>

js的引入方式和输出方式

引入方式

第一种、在body标签中嵌入script标签

<body class="one">
<script>
    //弹出框
    // alert("弹出框");
    //页面输出
    // document.write("页面输出");
    //控制台输出
    console.log("控制台输出");
</script>
</body>

第二种、引入本地独立js文件

本地有js文件,在body标签中嵌入script标签,引入本地js文件,使用src属性指定js文件的路径,

type属性指定js文件的类型,默认是text/javascript

<script src="./one.js" type="text/javascript"></script>

第三种、引入网络来源文件

​<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js" type="text/javascript">/script>

输出方式

第一种、弹出框

alert("弹出框");

第二种、页面输出

document.write("页面输出");

第三种、控制台输出

console.log("控制台输出");

代码 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第四章 js 引入方式</title>
</head>
<body class="one">
<h1>第四章 js 引入方式</h1>
  //第二种
<script src="./one.js" type="text/javascript"></script>
  //第三种
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js" type="text/javascript"></script>
  //第一种
<script>
    //弹出框
    // alert("弹出框");
    //页面输出
    // document.write("页面输出");
    //控制台输出
    console.log("控制台输出");
</script>
</body>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</html>

js数据类型

一、数据类型分为

ES5六种:🔴数值类型、🔴字符串类型、🔴布尔类型、⭕undefined类型、⭕null类型、❗对象类型

(ECMAScript 5 也称为 ES5 和 ECMAScript 2009。--可以理解为是js语言规范标准的版本)

原始数据类型(基本):数值类型、字符串类型、布尔类型

合成类型(复合类型):对象类型

特殊值:undefined类型、null类型

二、js类型转换

转为String:

方法一: toString() ⛳

方法二:String()强制转换 ⛳

方法三:加号拼接字符串⛳

转为数字类型:

1⛳parseInt()函数

2⛳parseFloat()函数

3⛳Number()强制转换

4⛳js隐式转换(- * /)

注意:NaN 表示number类型的非数字

转为布尔类型:true/false

Boolean()强制转换

只有null,undefined,NaN,"",0五种为false,其他都为true

三、typeof 判断基本数据类型

代码

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>第五章 js 数据类型</title>
</head>
<body class="one">
<h1> 第五章 数据类型</h1>

<script>

    let a = 1;
    console.log("数值类型a:", a);
    let b = "1";
    console.log("字符串类型b:", b);
    //0-false 1-true
    let c = true;
    console.log("布尔类型c:", c);

    //复合 object(对象)
    let student = {
        name: "张三",
        age: 18,
        sex: "男",
        isMarry: false,

    }

    //转为String三种方式
    var num=10;
    console.log("转为String:", num.toString());//10
    console.log("转为String:", String(num));//10
    console.log("转为String:", num+"");//10

    //转为数字类型:parseInt()函数 parseFloat()函数  Number()强制转换  js隐式转换(- * /)
    //NaN 表示number类型的非数字
    var str="123.22";
    console.log("转为数字类型:", parseInt(str));//123
    console.log("转为数字类型:", parseFloat(str));//123.22
    console.log("转为数字类型:", Number(str));//123.22
    console.log("转为数字类型:", str-0);//123.22
    var str1="re120px";
    console.log("转为数字类型:", parseInt(str1));//NaN
    console.log("转为数字类型:", parseFloat(str1));//NaN
    console.log("转为数字类型:", Number(str1));//NaN
    console.log("转为数字类型:", str1-0);//NaN
    console.log("转为数字类型:", "123"-"120");//3

    //布尔类型
    console.log("转为布尔类型:", Boolean(0));//false
    console.log("转为布尔类型:", Boolean(1));//true
    console.log("转为布尔类型2:", Boolean(2));//true
    console.log("转为布尔类型:", Boolean(""));//false
    console.log("转为布尔类型:", Boolean(" "));//true
    console.log("转为布尔类型:", Boolean(null));//false
    console.log("转为布尔类型:", Boolean(undefined));//false
    console.log("转为布尔类型:", Boolean(NaN));//false


    //typeof 判断基本数据类型
    console.log("typeof判断基本数据类型:", typeof 1);//number
    console.log("typeof判断基本数据类型:", typeof "1");//string
    console.log("typeof判断基本数据类型:", typeof true);//boolean
    console.log("typeof判断基本数据类型:", typeof null);//object
    console.log("typeof判断基本数据类型:", typeof undefined);//undefined
    console.log("typeof判断基本数据类型:", typeof student);//object
    console.log("typeof判断基本数据类型:", typeof [1,2,3]);//object
    //null 一般代表对象为没有,undefined代表数值没有
</script>


</body>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</html>

js运算符

一、算数运算符

加法运算符:+

减法运算符:-

乘法运算符:*

除法运算符:/

取余运算符:%

自增运算符:++     ++num:先自增再运算 num++:先运算再自增

自减运算符:--

二、赋值运算符

=等于运算符

+=等同于 a=a+b

-=等于 a=a-b

*=等于 a=a*b

/=等于 a=a/b

%=等于 a=a%b

三、比较运算符

== 相等运算符

=== 严格相等运算符

!= 不相等运算符

!== 严格不等运算符

> 大于运算符

>= 大于等于运算符

< 小于运算符

<= 小于等于运算符

四、布尔运算符

&& 与运算符 多个条件都为true 才为true

|| 或运算符 多个条件只要有一个为true 就为true

! 取反运算符

注意:非布尔取反

对于非布尔值 取反运算符会将其转为布尔 undefined null NaN 0 -0 "" false 返回true 其余都为false

五、三元运算符

表达式? 'Welcome back!' : 'Please sign in.');

//表达式true返回:前的,false返回:后的

六、运算符优先级

参考:Javascript中的运算符及其优先级顺序_js运算符优先级-CSDN博客

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第六章、js 运算符</title>
</head>
<body class="one">
<h1>第六章 js 运算符</h1>
<script>
    //算数运算符
    let a = 1;
    let b = 2;
    console.log("a+b", a + b);//3
    console.log("a-b", a - b);//-1
    console.log("a*b", a * b);//2
    console.log("a/b", a / b);//0.5
    console.log("a%b", a % b);//1
    console.log("a++", a++,a);//1 2
    console.log("a--", a--,a);//2 1
    console.log("++a", ++a,a);//2  2
   console.log("--a", --a,a);//1  1
    let  c=20;
    console.log("++c", ++c);//21 先增再打印
    console.log("--c", --c);//20 先减再打印
    console.log("c++", c++);//20 先打印再减
    console.log("c--", c--);//21 先打印再增

    //赋值
    let d = 1;
    let e = 2;
    console.log("d+=e", d += e);//3 相当于d=d+e
    console.log("d-=e", d -= e);//1 相当于d=d-e
    console.log("d*=e", d *= e);//2
    console.log("d/=e", d /= e);//1
    console.log("d%=e", d %= e);//1


    //比较运算符
    let f = 10;
    let g = "10";
    console.log("f==g", f == g);//true
    console.log("f===g", f === g);//false
    console.log("f!=g", f != g);//false
    console.log("f!==g", f !== g);//true


    //布尔运算符

    console.log("!null", !null);//true
    console.log("!100", !100);//false

     //&&逻辑与 ||逻辑或
    console.log(100>10 && 100<20 && 100>5) //false
    console.log(100>10 && 100>20 && 100>10) //true

    console.log(100>10 || 100<20 || 100>5) //true
    console.log(100>10 || 100>20 || 100>10) //true
    console.log(100<10 || 100<20 || 100<10) //false

    // 示例 1: 使用 && 进行条件判断
    let aa = true;
    let bb = false;

    console.log(aa && bb);  // 输出: false

    // 示例 2: 短路求值
    let cc = 0;
    let dd = 10;

    console.log(cc && dd);  // 输出: 0 (因为 cc 为 false,所以直接返回 c)

    // 示例 3: 返回值
    let ee = 1;
    let ff = 2;

    console.log(ee && ff);  // 输出: 2 (因为 e 和 f 都为 true,所以返回 f 的值)


    console.log("三元",10>1 ? 'Welcome back!' : 'Please sign in.');//true返回:前的,false返回:后的
</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</body>
</html>

js流程控制

包括:顺序、分支、循环

一、顺序流程控制

最简单的流程控制:没有特定的语法结构,按照代码的顺序执行

二、分支流程控制

if语句

三元表达式

switch 语句

if和switch语句区别

一般情况下,if语句和switch语句都可以实现分支控制,可以相互替换

switch语句通常处理case为比较确定值的情况,而if else更灵活,常用于范围判断

switch进行条件判断后直接进入程序条件语句,效率更高,而if else得判断多次

当分支比较少的时候,if else更适合,如果分支比较多,switch语句更适合

三、循环流程控制

for 循环

while 循环

do...while 循环

continue break 关键字区别

continue跳出本次循环:跳出本次循环,继续下一次循环

break跳出循环:跳出循环,不再执行循环代码(循环结束)

四、调试打断点

F12 sources 找到需要调试的文件 设置断点

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第七章、js 流程控制</title>
</head>
<body class="one">

<script>

    //if语句
    let a = 10;
    if (a > 10) {
        console.log("a大于10");
    } else {
        console.log("a小于等于10");
    }
    //if-else语句
    let b = 10;
    if (b > 10) {
        console.log("b大于10");
    } else if (b === 10) {
        console.log("b等于10");
    } else {
        console.log("b小于等于10");
    }

    //三元表达式
    let c = 10;
    console.log(c > 10 ? "c大于10" : "c小于等于10");

    //switch语句
    switch (c) {
        case 10:
            console.log("c等于10");
            break;
        case 20:
            console.log("c等于20");
            break;
        default:
            console.log("c不等于10和20");
            break;
    }

    //for 循环
    console.log("for 循环");
    for (let i = 0; i < 10; i++) {
        console.log("i的值为:", i);
    }
    console.log("continue跳出本次循环");
    //continue跳出本次循环
    for (let i = 0; i < 10; i++) {
        if (i === 5) {
            continue;
        }
        console.log("i的值为:", i);
    }
    //break 跳出循环
    console.log("break跳出循环");
    for (let i = 0; i < 10; i++) {
        if (i === 5) {
            break;
        }
        console.log("i的值为:", i);
    }
    //while 循环
    console.log("while 循环");
    let i = 0;
    while (i < 10) {
        console.log("i的值为:", i);
        i++;
    }
    //do...while 循环
    console.log("do...while 循环");
    let j = 0;
    do {
        console.log("j的值为:", j);
        j++;
    } while (j < 10);

</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</body>
</html>

js字符串及方法

转义

转义字符:

转义字符:\n 换行

方法

二、length 字符串长度

三、charAt(index) 获取字符串指定位置的字符,从0开始;参数大于长度返回空字符串

四、concat() 字符串拼接

五、indexOf(str) 查找指定字符串的位置,从0开始,找不到返回-1

六、lastIndexOf(str) 查找指定字符串的位置,从后往前,找不到返回-1

七、substring(start,end) 截取字符串,start开始位置,end结束位置,不包含end

八、substr(start,length) 截取字符串,start开始位置,length截取长度

九、slice(start,end) 截取字符串,start开始位置,end结束位置,包含start,不包含end

十、trim() 去掉字符串前后空格

十一、replace(str,str1) 替换字符串

十二、toUpperCase() 字符串转大写

十三、toLowerCase() 字符串转小写

十四、split(str) 字符串分割,返回数组

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第八章、字符串</title>
</head>
<body class="one">
<script>
   //字符串转义
   let str = "hello\nworld";
   console.log("换行",str);
   //转义
   let str1 = "hello world\"你好\"";
   console.log("引号",str1);

   //length 字符串长度
   let str2 = "hello world";
   console.log("字符串长度",str2.length);//11
   //charAt(index) 指定位置的字符
   for (let i = 0; i < str2.length; i++) {
       console.log("字符串chartAt",str2.charAt(i));
   }
   console.log("字符串最后一位",str2.charAt(str2.length-1));//d

   //字符串拼接
   let str3 = "hello";
   let str4 = "world";
   console.log("字符串拼接",str3.concat(str4));//helloworld


   //indexof(str) 查找指定字符串的位置,从0开始,找不到返回-1
   let str5 = "hello world";
   console.log("字符串indexOf",str5.indexOf("world"));//6
   console.log("字符串indexOf",str5.indexOf("world1"));//-1

   //lastIndexOf(str) 查找指定字符串的位置,从后往前,找不到返回-1
   let str6 = "hello world";
   console.log("字符串lastIndexOf",str6.lastIndexOf("world"));//6
   console.log("字符串lastIndexOf",str6.lastIndexOf("world1"));//-1

   //substring(start,end) 截取字符串,start开始位置,end结束位置,不包含end
   let str11 = "hello world";
   console.log("字符串substring",str11.substring(0,5));//hello
   console.log("字符串substring",str11.substring(6,11));//world

   //substr(start,length) 截取字符串,start开始位置,length截取长度
   let str7 = "hello world";
   console.log("字符串substr",str7.substr(0,5));//hello
   console.log("字符串substr",str7.substr(6,5));//world

   //slice(start,end) 截取字符串,start开始位置,end结束位置,包含start,不包含end
   let str8 = "hello world";
   console.log("字符串slice",str8.slice(0,5));//hello
   console.log("字符串slice",str8.slice(6,11));//world

   //trim() 去掉字符串前后空格
   let str9 = " hello world ";
   console.log("字符串trim",str9.trim());//hello world

   //replace(str,str1) 替换字符串
   let str10 = "hello world";
   console.log("字符串replace",str10.replace("world","java"));//hello java

   //toUpperCase() 字符串转大写
   let str10 = "hello world";
   console.log("字符串toUpperCase",str10.toUpperCase());//HELLO WORLD

   //toLowerCase() 字符串转小写
   let str11 = "HELLO WORLD";
   console.log("字符串toLowerCase",str11.toLowerCase());//hello world

   //split(str) 字符串分割,返回数组
   let str12 = "hello world";
   console.log("字符串split",str12.split(" "));//["hello", "world"]、
   console.log("字符串split",str12.split(""));//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]


</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</body>
</html>

js数组

概念(定义与赋值)

按次序排列的一组值,每个值的位置都有编号(从0开始),整个数组用方括号表示
可以先定义再赋值 ,也可以直接定义并赋值

 数组元素可以是任何数据类型
如果数组的元素还是数组,就形成多维数组

常用方法

  1. length 数组长度
  2. 获取数组元素 数组名[索引]
  3. 数组遍历方法 for
  4. 数组的静态方法Array.isArray()
  5. 数组的方法:push 数组末端添加元素(一个或多个),并返回新数组的长度。注意:会改变原数组
  6. 数组的方法:pop 数组末端删除元素(最后一个),并返回删除的元素。注意:会改变原数组
  7. 数组的方法:shift 数组首部删除元素(第一个),并返回删除的元素。注意:会改变原数组
  8. 数组的方法:unshift 数组首部添加元素(一个或多个),并返回新数组的长度。注意:会改变原数组
  9. 数组的方法:join (指定参数作为分隔符)将数组元素连接为一个字符串,并返回该字符串。注意:不会改变原数组;如果不提供参数,默认逗号分隔
  10. 数组的方法:concat 数组合并,并返回合并后的数组。注意:不会改变原数组
  11. 数组的方法: reverse 数组反转,并返回反转后的数组。注意:会改变原数组
  12. 数组的方法:sort 数组排序,并返回排序后的数组。注意:会改变原数组
  13. 数组的方法:splice 数组删除或替换元素,并返回被删除的元素。注意:会改变原数组
  14. 数组的方法:slice 数组截取,并返回被截取的元素。注意:不会改变原数组
  15. 数组的方法:indexOf 数组查找元素,并返回元素在数组中的位置。注意:返回的是索引,找不到返回-1


代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第九章、数组</title>
</head>
<body class="one">
<h1>数组</h1>
<script>

    //数组定义并赋值
    let arr = [1, 2, 3, 4, 5];
    console.log("数组arr", arr);

    //先定义再赋值
    let arr1 = new Array(1, 2, 3, 4, 5);
    console.log("arr1", arr1);

    let arr2 = [];
    arr2[0] = "a";
    arr2[1] = "b";
    arr2[2] = "c";
    console.log("数组arr2", arr2);


    let arr3 = [1, 2, ["one", "two"]];
    console.log("数组arr3", arr3);//获取数组arr3的第3个数组
    console.log("数组arr3", arr3[2][1]);//获取数组arr3的第3个数组的第2个元素 two
    console.log("输出不存在的结果", arr3[5]);//undefined 数组越界


    //数组遍历
    for (let i = 0; i < arr.length; i++) {
        console.log("遍历数组arr", arr[i]);
    }
    //while循环
    let i = 0;
    while (i < arr.length) {
        console.log("遍历数组arr", arr[i]);
        i++;
    }
    //for of循环
    for (let item of arr) {
        console.log("遍历数组arr", item);
    }
    //for in循环
    for (let i in arr) {
        console.log("遍历数组arr", arr[i]);
    }

    //for of 与for in 区别---拓展
    //for...in 更适合用于遍历对象的属性。
    //for...of 更适合用于遍历数组或类似数组的集合。

    //数组的静态方法Array.isArray()
    console.log("判断arr是否是数组",typeof  arr);//object    数组的关键字 Array
    console.log("判断arr是否是数组", Array.isArray(arr));//true

    //push 数组末端添加元素,并返回新数组的长度。注意:会改变原数组
    let arr4 = [1, 2, 3, 4, 5];
    console.log("数组arr4", arr4);
    console.log("arr4.push(6)", arr4.push(6));
    console.log("数组arr4", arr4);
    console.log("arr4.push(7, 8, 9, 10)", arr4.push(7, 8, 9, 10));
    console.log("数组arr4", arr4);

    //pop 数组末端删除元素,并返回删除的元素。注意:会改变原数组
    let arr5 = [1, 2, 3, 4, 5];
    console.log("数组arr5", arr5);
    console.log("arr5.pop()", arr5.pop());
    console.log("数组arr5", arr5);

    //shift 数组首部删除元素,并返回删除的元素。注意:会改变原数组
    let arr6 = [1, 2, 3, 4, 5];
    console.log("数组arr6", arr6);
    console.log("arr6.shift()", arr6.shift());
    console.log("数组arr6", arr6);
    //遍历删除每一个
    while (arr6.length > 0) {
        console.log("遍历删除每一个", arr6.shift());
    }
    console.log("数组arr6", arr6);

    //unshift 数组首部添加元素,并返回新数组的长度。注意:会改变原数组
    let arr7 = [1, 2, 3, 4, 5];
    console.log("数组arr7", arr7);
    console.log("arr7.unshift(0)", arr7.unshift(0));
    console.log("数组arr7", arr7);
    console.log("arr7.unshift(0, 1, 2, 3, 4, 5)", arr7.unshift(0, 1, 2, 3, 4, 5));
    console.log("数组arr7", arr7);


    //join (指定参数作为分隔符)将数组元素连接为一个字符串,并返回该字符串。注意:不会改变原数组
    let arr8 = [1, 2, 3, 4, 5];
    console.log("数组arr8", arr8);
    console.log("arr8.join()", arr8.join());
    console.log("arr8.join('-')", arr8.join("-"));
    console.log("数组arr8", arr8);//不改变原数组
    let arr9 = [1, 2, 3, 4, 5,null,undefined,""];
    console.log("数组arr9", arr9);
    console.log("arr9.join('-')", arr9.join("-"));//数组成员是undefined或null或空位,会被转为空字符串


    //concat 数组合并,并返回合并后的数组。注意:不会改变原数组
    let arr10 = [1, 2, 3, 4, 5];
    let arr11 = [6, 7, 8, 9, 10];
    console.log("数组arr10", arr10);
    console.log("数组arr11", arr11);
    console.log("arr10.concat(arr11)", arr10.concat(arr11));
    console.log("arr10", arr10);//不改变原数组
    console.log("测试合并", [1,2,3].concat([4,5,6],[7,8,9],[10,11,12],13,14));//合并数组 [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

    //reverse 数组反转,并返回反转后的数组。注意:会改变原数组
    let arr12 = [1, 2, 3, 4, 5];
    console.log("数组arr12", arr12);
    console.log("arr12.reverse()", arr12.reverse());
    console.log("数组arr12", arr12);
    //字符串反转
    let str = "abcdefg";
    console.log("字符串反转", str);//str.split(""):将字符串str分割成字符数组,
    console.log("字符串反转", str.split("").reverse().join(""));


    //sort 数组排序,并返回排序后的数组。注意:会改变原数组
    let arr13 = [1, 2, 6, 4, 5];
    console.log("数组arr13", arr13);
    console.log("arr13.sort()", arr13.sort());//数组元素是数字,按照数值大小排序 [1, 2, 4, 5, 6]

</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</body>
</html>

js函数

定义:

封装了一块可被重复调用执行的代码块

使用:

函数声明和函数调用

声明函数:

function 函数名(参数1,参数2,参数3){函数体}<br> 调用函数:函数名(参数1,参数2,参数3)

函数提升:

先调用后创建也可以,在编译代码的时候,会把函数提升到顶部 (类似变量提升)

形参和实参:

参是函数定义时定义的参数,实参是函数调用时传递的参数,多个参数逗号分隔,也可以不带参数

函数的返回值:return 值 没有返回值,默认返回undefined
函数不调用,不执行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>函数的使用</title>
</head>
<body class="one">
<h1>函数</h1>
<script>

    let a = add(5, 6)
    console.log("add函数的返回值为:", a)

    //函数声明
    function add(a, b) {
        console.log("a的值为:", a);
        console.log("b的值为:", b);
        console.log("a+b的值为:", a + b);
        return a + b;
        //return 后面的代码不会执行
    }

    //函数调用--可复用
    add(1, 2);
    add(3, 4);

</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
</style>
</body>

</html>

js对象

现实中的对象:万物皆对象,对象是一个具体的事物,看得见摸得着的实物,例如一本书、一辆汽车、一个 enzymes、一个网站等等。

一、概念:

对象是一组无序的相关属性和方法的集合,属性是键值对,属性名是键,属性值是值。

二、组成:

对象是由属性和方法组成的。

属性:事物的特征
方法:事物的行为

三、读取(调用)方式:

1.点语法:obj.name;

2.方括号语法:obj["name"];

四、创建对象方式:

    1.字面量创建对象
    2.new Object 创建对象
    3.构造函数创建对象

五、构造函数:

是一种特殊函数,主要用来初始化对象,即为对象成员变量赋初始值,她总要与new运算符一起使用。我们可以把对象中的一些公共的属性和方法抽取出来,封装到这个函数里面

1、构造函数约定首字母大写
2、函数内的属性和方法前面需要添加this关键字,表示当前对象的属性和方法
3、构造函数中不需要return返回结果
4、创建对象时,必须使用new来调用构造函数

六、new关键字的作用:

1、在内存中创建一个新的空对象
2、让this指向新创建的对象
3、执行构造函数中的代码,再给这个新对象添加属性和方法
4、返回这个新的对象(所以构造函数里面不需要return)


对象遍历: for...in循环

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>对象</title>
</head>
<body class="one">
<h1>对象</h1>
<script>

    //字面量创建对象
    //创建一个对象,键值对
    //值可以是任意数据类型:字符串、数字、布尔值、数组、对象、函数(方法)
    let obj = {
        name: "张三",
        age: 18,
        sex: "男",
        say: function () {
            console.log("我是一个对象");
        },
        friends: ["李四", "王五", "赵六"],
        isMan: true,
        address: {
            province: "北京",
            city: "北京"
        }
    };

    //访问对象属性中的方法
    obj.say();
    console.log("访问对象属性中的方法", obj.friends[0]);
    //链式调用
    console.log("访问对象属性中的方法", obj.address.province);

    for (let i = 0; i < obj.friends.length; i++) {
        console.log("访问对象属性中的方法", obj.friends[i]);
    }
console.log("---------------------------------------------")

    //new Object 创建对象
    let obj1 = new Object();
    obj1.name = "张三";
    obj1.age = 18;
    obj1.sex = "男";
    obj1.say = function () {
        console.log("我是一个对象");
    };
    console.log("new Object 创建对象", obj1);
    console.log("new Object 创建对象", obj1.say);
    console.log("new Object 创建对象", obj1.say());


console.log("------------------------------------------------")

    //构造函数创建对象
    function Person(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.say = function () {
            console.log("我是一个对象");
        };
        this.friends = ["李四", "王五", "赵六"];
        this.isMan = true;
        this.address = {
            province: "北京",
            city: "北京"
        };
    }
    let person = new Person("张三", 18, "男");
    console.log("构造函数创建对象", person);
    console.log("构造函数创建对象", person.say);
    console.log("构造函数创建对象", person.say());


</script>
<style> .one {
    background-color: #a5c5c2;
    /*字体*/
    font-family: "微软雅黑";
    font-size: 20px;
}</style>
</body>
</html>

内置对象


一、概念:

内置对象是js自带的一些对象,供开发者使用,提供一些常用的基本的功能(属性和方法)。
内置对象的有点是帮助我们快速开发


多种内置对象:Math、Date、String、Array、RegExp、Object、Function、Number、Boolean、Error、JSON

MDN查找内置对象:JavaScript 标准内置对象 - JavaScript | MDN (mozilla.org)

 二、Math:

Math对象提供一些数学相关的常量和函数。

三、Date:

Date对象表示日期和时间

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>内置对象</title>
</head>
<body class="one">
<h1>内置对象</h1>


<h3>Math:Math对象提供一些数学相关的常量和函数。</h3>
Math.PI;//圆周率<br>
Math.floor();//向下取整<br>
Math.ceil();//向上取整<br>
Math.random();//随机数<br>
Math.sqrt();//平方根<br>
Math.abs();//绝对值<br>
Math.max();//最大值<br>
Math.min();//最小值<br>
Math.pow();//幂运算<br>
Math.sqrt();//平方根<br>

<h3>Date:Date对象表示日期和时间。</h3>
Date是一个构造函数,需要实例化才可以使用<br>
new Date();//创建一个日期对象<br>
new Date(dateString);//创建一个日期对象<br>
new Date(year, month, day, hours, minutes, seconds, milliseconds);//创建一个日期对象<br>
new Date(milliseconds);//创建一个日期对象<br>
new Date().getFullYear();//获取年份<br>
new Date().getMonth();//获取月份<br>
new Date().getDate();//获取日期<br>
new Date().getDay();//获取星期几<br>
new Date().getHours();//获取小时<br>
new Date().getMinutes();//获取分钟<br>
new Date().getSeconds();//获取秒数<br>
new Date().getTime();//获取时间戳<br>
new Date().toLocaleString();//获取本地时间<br>
new Date().toUTCString();//获取UTC时间<br>
new Date().toDateString();//获取日期字符串<br>
new Date().toTimeString();//获取时间字符串<br>
new Date().toLocaleDateString();//获取本地日期字符串<br>
new Date().toLocaleTimeString();//获取本地时间字符串<br>





<script>

    //math.abs 求绝对值
    console.log("math.abs 求绝对值", Math.abs(-10));
    //math.ceil 向上取整
    console.log("math.ceil 向上取整", Math.ceil(10.1));
    //math.floor 向下取整
    console.log("math.floor 向下取整", Math.floor(10.9));
    //math.round 四舍五入
    console.log("math.round 四舍五入", Math.round(10.5));
    //math.random 随机数
    console.log("math.random 随机数", Math.random());
    console.log("math.random 随机数", Math.random() * 10);
    //math.max 最大值
    console.log("math.max 最大值", Math.max(1, 2, 3, 4, 5));
    //math.min 最小值
    console.log("math.min 最小值", Math.min(1, 2, 3, 4, 5));

    //Date
    console.log("Date", new Date());
    console.log("Date", new Date(Date.parse("2020-01-01")));
    console.log("Date", new Date(2020, 0, 1, 0, 0, 0, 0));
    console.log("Date", new Date(0));//格林威治时间1970年1月1日0时0分0秒
    console.log("Date", new Date().getFullYear());//获取年份??
    console.log("Date", new Date().getMonth()+1);//获取月份
    console.log("Date", new Date().getDate());//获取日期
    console.log("Date", new Date().getDay());//获取星期几
    console.log("Date", new Date().getHours());//获取小时
    console.log("Date", new Date().getMinutes());//获取分钟
    console.log("Date", new Date().getSeconds());//获取秒数
    console.log("Date", new Date().getTime());//时间戳 格林威治时间到现在的时间差
    console.log("Date", new Date().toLocaleString());

</script>
<style> .one {
    background-color: #a5c5c2;
    /*字体*/
    font-family: "微软雅黑";
    font-size: 20px;
}</style>
</body>
</html>

DOM-文档对象模型

 一、DOM概念:

js操作页面的中间点,操作页面的接口

 DOM树
文档:页面就是一个文档,DOM中使用document表示
元素:页面中的所有标签都是元素,DOM中使用element表示
节点:文档中的所有内容都是节点,节点包括元素节点、属性节点、文本节点、注释节点等 ,DOM中使用node表示

二、 document对象_方法 获取元素

document.getElementById() 获取带有ID的元素对象
 document.getElementsByTagName() 获取元素标签名
 document.getElementsByClassName() 获取带有class的元素对象

 document.getElementsByName() 获取带有name的元素对象

document.querySelector() 获取带有css选择器的元素对象
document.querySelectorAll() 获取带有css选择器的元素对象

三、document对象_方法 创建元素

 document.createElement() 创建元素
document.createTextNode() 创建文本节点
 document.createAttribute() 创建属性节点
document.createComment() 创建注释节点

四、 element对象_属性

Element.id 获取id属性
Element.className 读写当前class属性,他的值是一个字符串,每个class之间用空格分割
 Element.classList 添加、删除、判断class属性,他的值是一个类数组对象


add():增加一个class属性
remove():删除一个class属性
contains():判断是否包含class属性
toggle():切换class属性(如果存在删除,不存在添加)

Element.innerHTML 读写当前元素内部的html内容

Element.innerText  只能识别文本,不能识别标签;会把标签识别成字符串

五、 element获取元素位置(过)

Element.offsetLeft 获取元素左边到浏览器左边的距离
Element.offsetTop 获取元素上边到浏览器上边的距离
Element.offsetWidth 获取元素宽度
Element.offsetHeight 获取元素高度
Element.clientHeight 获取元素内容高度,包括padding 不包括border和margin 
Element.clientWidth 获取元素内容宽度,包括padding 不包括border和margin
 Element.scrollHeight 获取元素内容高度 
Element.scrollWidth 获取元素内容宽度

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM</title>
</head>
<body class="one">
<h1 id="one"> DOM-文档对象模型</h1>
<script>
    //获取id为one的元素(唯一的)
    console.log(document.getElementById("one"));
    //根据html标签名获取
    console.log(document.getElementsByTagName("h4"));
    console.log(document.getElementsByTagName("h4")[0]);

    //根据class获取
    console.log(document.getElementsByClassName("two"));
    let two = document.getElementsByClassName("two")[0];
    console.log(two);
    // two.innerHTML = "Hello";

    //根据name获取(不常用)
    console.log("根据name获取", document.getElementsByName("name"));
    console.log("根据name获取", document.getElementsByName("name")[0]);

    //根据css选择器获取
    console.log("根据css选择器获取", document.querySelector(".one"));

    console.log("---------------------------------------");


    //创建元素
    let div = document.createElement("div");
    //创建文本
    let text = document.createTextNode("Hello");
    console.log("创建文本", text);
    //将子元素放入容器中
    div.appendChild(text);
    console.log("创建元素", div);
    //创建属性
    var id = document.createAttribute("id")
    //设置属性值
    id.value = "root";
    console.log("创建属性", id);
    //将属性放入容器中
    div.setAttributeNode(id);
    console.log("创建元素", div);
    //显示到div的id为container中
    document.getElementById("container").appendChild(div);
    console.log("---------------------------------------");


    let root = document.getElementById("root1");
    //修改属性
    root.id = "root2";
    console.log("root.className", root.className)
    //修改class
    // root.className = "box box1";
    //添加class属性
    // console.log("root.classList.add", root.classList.add("box1"))
    //移除class属性
    // root.classList.remove("box");
    //判断有无某属性
    // console.log("root.classList.contains", root.classList.contains("box"));


    //innerHTML 与 innerText 的 区别
    let str="<a href='https://www.baidu.com'>百度</a>"
    // root.innerHTML = str;
    // root.innerText = str;

</script>
<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }

    .box {
        font-size: 30px;
    }

    .box1 {
        background-color: #764fa5;
    }
</style>
</body>
</html>

js 事件

 一、事件处理程序

1、html事件
2、DOM0级事件
3、DOM2级事件

二、鼠标事件

1、onclick 事件  按下鼠标时触发<br>
2、dblclick 事件  双击鼠标时触发<br>
3、mounsedown 事件  按下鼠标时触发<br>
4、mouseup 事件  松开鼠标时触发<br>
5、mousemove 事件  鼠标移动时触发<br>
6、mouseenter 事件  鼠标进入元素时触发<br>
7、mouseleave 事件  鼠标离开元素时触发<br>
8、mouseover 事件  鼠标进入元素时触发<br>
9、mouseout 事件  鼠标离开元素时触发<br>
10、wheel 事件  鼠标滚轮滚动时触发<br>

 三、Event事件对象

事件发生以后,会产生一个事件对象,作为参数传递给监听函数

Event事件对象属性
1、event.target 事件目标元素
2、event.type 事件类型


Event事件对象方法
1、event.preventDefault() 阻止默认行为  比如说点击按钮弹框,使用之后就不弹框了
2、event.stopPropagation() 阻止事件冒泡

 四、键盘事件  

键盘事件由用户击打键盘的时候触发,主要 有keydown keyup keypress 事件
keydown 事件 按下键盘时触发
keypress 事件 按下有值的键时触发(ctrl alt是无值的)
keyup 事件 释放键盘时触发


五、表单事件 

表单事件是在使用表单元素及输入框元素可以监听的一系列事件
1、input事件 输入框内容发生改变时触发
2、change 事件 输入框内容发生改变时触发;失去焦点时触发
3、select 事件 选择框内容发生改变时触发
4、submit 事件 提交表单时触发
5、reset 事件 重置表单时触发

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js 事件</title>
</head>
<body class="one">
<h1 id="one"> js 事件</h1>
<button onClick="handleClick()">html事件</button>
<hr>
<button id="btn">dom0级事件</button>
<hr>
<button id="btn1">dom2级事件</button>
<hr>
<button id="btn2">双击事件</button>
<hr>
<button id="btn3" class="btn3">移动事件</button>
<hr>
<button id="btn4">event事件对象</button>
<hr>
<input type="text" id="username" placeholder="键盘事件"/>

<hr>
<input type="text" id="username1" placeholder="输入框input事件"/>
<hr>
<form action="服务器地址" id="myForm" onsubmit="submentHandle">
    <input type="text" id="username2" placeholder="表单事件"/>
    <button type="submit">提交</button>
    <button type="reset" id="resetBtn">重置</button>

</form>
<script>
    //html事件 缺点:Html与js没有分开
    function handleClick() {
        console.log("html事件");
    }


    //适用于一个事件的
    //dom0级事件 优点:Html与js分开  缺点:无法同时添加多个事件
    document.getElementById("btn").onclick = function () {
        console.log("dom0级事件1");//被覆盖了
    }
    document.getElementById("btn").onclick = function () {
        console.log("dom0级事件2");
    }


    //使用多种事件的
    //dom2级事件 优点:Html与js分开 ; 可以同时添加多个事件,不回被覆盖;  缺点:写法麻烦
    document.getElementById("btn1").addEventListener("click", function () {
        console.log("dom2级事件1");
    })
    document.getElementById("btn1").addEventListener("click", function () {
        console.log("dom2级事件2");
    })


    //双击事件
    document.getElementById("btn2").ondblclick = function () {
        console.log("双击事件");
    }

    //btn3鼠标移动事件
    document.getElementById("btn3").onmousemove = function () {
        console.log("鼠标移动事件");
    }


    //event事件对象
    document.getElementById("btn4").onclick = function (event) {
        console.log("event事件对象event", event);
        console.log("event事件对象target", event.target);
        console.log("event事件对象type", event.type);
        event.target.innerHTML = "点击之后";
    }


    //键盘keydown 事件
    document.getElementById("username").onkeydown = function (event) {
        console.log("keydown事件", event);
        if (event.keyCode === 13) {
            console.log("按下了回车");
        }
    }
    document.getElementById("username").onkeyup = function (event) {
        console.log("keyup事件", event);
        if (event.keyCode === 13) {
            console.log("抬起了回车");
        }
    }

    //input事件
    document.getElementById("username1").oninput = function (event) {
        console.log("input事件", event.target.value);
    }
    //change事件
    document.getElementById("username1").onchange = function (event) {
        console.log("change事件", event.target.value);
    }
    //select事件
    document.getElementById("username1").onselect = function (event) {
        console.log("select事件", event.target.value);
    }

    let resetBtn = document.getElementById("resetBtn");
    let myForm=document.getElementById("myForm");
    //重置表单
    resetBtn.onclick=function (event) {
        myForm.reset();
    }
    //提交表单
    function submentHandle(event) {
        console.log("表单事件", event);
    }


</script>

<style>
    .one {
        background-color: #a5c5c2;
        /*字体*/
        font-family: "微软雅黑";
        font-size: 20px;
    }
    .btn3{
        width: 100px;
        height: 100px;
        background-color: #347dda
    }
</style>
</body>
</html>


文章来源:https://blog.csdn.net/m0_63456808/article/details/140965077
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云