javaScript基础
基础语法
输出
- window.alert()
- document.write()
- document.getElementByXX.innerHtml = ''
- innerHtml 插入html代码块
- innerText 插入文本内容
- value获取input类型的组件的输入值
window.alert("hello world!");
document.write("hello world2!");
// 这是一行注释
/*
* 这是多行注释 语法基本上和java相同
*/
let text = document.getElementById("input").value;
console.log(text);
let span = document.getElementById("text").innerText = text;
document.getElementById("text2").innerHTML = '<h1>html段</h1>';
console.log("hello world!!!");
变量
- var 没有作用域的变量 可以在定义前使用,var xxxx = 1 相当于window.xxx = 1
- let 有作用域的变量
- const 定义常量 const定义的变量不能重新赋值,也是跟java一样,不能修改引用,如果指向的是复杂对象可以修改此对象的值
// var 定义全局变量
// let 定义局部变量 const定义常量 const定义的变量不能重新赋值
// 重复定义变量但是不赋值 不会丢失原来的值 java重复定义变量会报错
// 奥~ 学到了 var原来还有这么多细节
// var声明的变量可以在声明前使用
var x = 3 + 4;
var x;
const s = 'hello world! l really like you very much! but i dont know how to express it';
const s2 = 'Her wistful face haunts my dreams like the rain at night. ha,ha,ha,ha';
let list = ["唱","rap","篮球"];
// 重新赋值会报错 s = 'ssss';
运算符
-
-
-
- / % ++ -- += -= **
-
-
- == 等值 === 等值且等型 != !== 不等值或者不等型 > < >= <= ? 三元运算符
- && || !
- typeof 返回变量的类型
- instanceof 判断是否是类的实现
- 位运算 & | ~ ^(异或) >> 有符号右移 << 零填充左移 >>> 零填充右移
console.log(x*1001);
window.alert(x*12121);
console.log(x instanceof String);
console.log(x instanceof Number)
console.log((x*-3)>>1);
console.log((x*-4)>>>2);
console.log(x<<2);
let object = {a:"111",b:"2"};
console.log(typeof object);
数据类型
- number 数值类型,可以使用科学计数法 3.14e5,3.14e-5
- String类型
- 数组 [1,3,4]
- 对象
- 对象和json字符串不同之处就是 key不用双引号
- json字符串为
- bigInt类型,用了来处理大整数
1.5 函数 定义和使用基本和java差不多
1.6 对象
var x = {
firstName:'',
lastName:'',
age:10,
fullName:function(){
return this.firstName + this.lastName;
}
}
调用对象内的函数
x.fullName 返回的是函数的定义
x.fullName() 调用函数
字符串处理函数
- length 固有属性 返回字符串的长度
- 查找字符串
- IndexOf("abc",3) 从第三个字符向后查找字符串abc首次出现的位置
- IndexOf("abc")
- lastIndexOf("abc") 从后向前查找首次出现abc的位置
- search("abc") 功能类似于indexOf 但是indexOf能够写正则表达式
- startsWith/endsWith
- match/matchAll 根据正则表达式查找匹配的字符串
- includs 字符串中是否包含某个字符串
- 截取字符串
- substr(start,length)
- 若省略第二个参数则截取到最后,第一个参数为负数,则从后向前查找
- slice(start,end)
- 若省略第二个参数则截取到最后,第一个参数为复数,则从后向前查找
- substring(start,end)
- 若省略第二个参数则截取到最后,第一个参数为复数,则从后向前查找
- substr(start,length)
- 替换字符串
- replace()
- 默认只会替换首个匹配的
- 使用正则表达式可以让它忽略大小写或者替换多个
- replace不会改变原来的字符串,会返回新字符串
- replace(/test/g,"text") 全局替换所有的test
- replace()
- trim() 去除字符串首尾空格
- 取某个字符
- charAt(index) 返回该位置的字符
- charCodeAt(index) 返回该位置的字符的ascii码
- 属性访问 直接使用s[1]来获取某个字符
- split() 字符串分割
- 模板字符串
- 允许在字符串中使用${}引用变量,写表达式
hello world ${x},${2*7+19},${s.length}
一般用来 动态生成表单之类的操作
- 允许在字符串中使用${}引用变量,写表达式
const s = 'hello world! l really like you very much! but i dont know how to express it';
console.log("s的长度" + s.length);
console.log(s.indexOf("or",1));
console.log(s.indexOf("or"));
console.log(s.lastIndexOf("or",50)); // 倒序查找到第五十个位置
console.log(s2.match(/ha/));
console.log(s2.matchAll(/ha/g));
console.log(s2.includes("ha"));
console.log(s.slice(0,3));
console.log(s.substring(1,18));
console.log(s.slice(-8,-1));
console.log(s.substr(0,10));
console.log(s.substr(10));
console.log(s2.replace(/ha/g,"good")); // 全局替换
console.log(s2.replace(/HA/i,"good")); // 不区分大小写
console.log(s2.charAt(1));
console.log(s2.charCodeAt(1));
for (const item of list) {
let li = document.createElement('li');
li.textContent = `我会 ${item == '篮球' ? '鸡哥打篮球真帅!鸡哥无敌' : item} `;
document.getElementById("list1").appendChild(li);
}
整数number常用操作
- toFixed() 返回带小数位数的数字
- 将javaScript变量转变为数字
- Number()
- parseFloat() 返回浮点数
- parseInt() 返回整数
let num = 3.1415926
console.log(num.toFixed(3)); // 保留三位
console.log(num.toFixed(4)); // 保留四位
console.log(Number(" 3.1343443"));
console.log(Number(" 333 3333 3333 ")); //NAN 不是数字
console.log(parseFloat("3.121111222"));
console.log(parseInt("1212131313"));
console.log(parseFloat("3.121111222 ")); // 自动去除空格
console.log(parseInt("666666655555.33333")); //处理时会自动忽略后面的小数
数组属性和常用操作
- length 返回数组的长度
- list.forEach(遍历方法) 遍历
- 遍历方法(项目值,项目索引,数组本身)
- Array.isArray(list) 判断对象是否是数组
- toString() 输出用,分割的字符串
- join(分割符号) 也是返回一串字符串,不过可以指定分割符
- pop() 从数组中弹出最后一个元素
- push() 在数组末端添加一个新元素
- shift() 删除首个元素,并且把其余元素向前位移一个位置
- unshift() 在数组头部添加新元素,其余元素向后位移一个位置
- delete list[x] 删除数组x下标的元素 undifined
- splice(开始位置,删除元素个数,"元素1","元素2",……) 数组拼接,返回值为删除元素的数组
- concat() 连接多个数组 可以传入多个参数,连接多个数组
- slice(起始位置,结束位置(不包含))
- indexOf(元素,[起始位置]) 返回该元素首次出现的下标
- lastIndexOf("Apple") 返回该元素最后出现的下标
- includes("Apple") 数组中是否包含Apple元素
- find(测试函数) 返回满足测试函数的首个元素
测试函数(元素值,元素索引,数组本身) - findIndex(测试函数) 返回满足测试函数的首个元素的索引
- findLast() 基本和find相同只是从后向前查找
- findLastIndex()
- sort() 以字母顺序进行排序
也可以传入一个函数 function(a,b) - reverse() 反转数组
- map(函数) 通过对数组每个元素执行函数来产生新的数组,不会影响原数组
函数(值,索引,数组) - filter(函数) 返回满足测试函数的新数组
- reduce(函数) 可以用来计算数字数组的和
函数(total,值,索引,数组本身) - reduceRight(函数) 基本和reduce相同 只不过是从右向左遍历
- every(测试函数) 检查每个值是否满足函数
测试函数(元素值,元素索引,数组本身) - some(测试函数) 是否有元素通过了测试函数
let list2 = ["abc","abd","abe","sde","ssdeaq"];
console.log("数组测试--------------》》》》》》");
console.log(list2.length);
console.log(list2.toString());
console.log(list2.join("@"));
console.log(list2.pop());
console.log(list2.toString());
console.log(list2.push("ssssssss")); //返回值是数组中元素个数
console.log(list2.toString());
console.log("是否是数组:" + Array.isArray(list2));
console.log(list2.shift());
console.log(list2.toString());
console.log(list2.unshift("bbbbdbddbbd")); //返回值是数组中元素个数
console.log(list2.toString());
let index = list2.indexOf("abe");
delete list2[index];
console.log(list2.toString());
list2[index] = 'aseds';
let list3 = ["cddede","frgt","desaw"];
let removes = list2.splice(2,2,"hello","zhansan","i like you");
console.log(list2.toString());
console.log(removes);
console.log("concat-------------->>>>>");
let list4 = list2.concat(list3,list); //返回新数组,不改变原数组的值
console.log(list4.toString());
console.log(list2);
console.log(list2.slice(2));
console.log(list2);
console.log(list2.slice(2,4));
console.log(list4.indexOf("frgt"));
console.log(list4.lastIndexOf("frgt"));
console.log(list4.includes("frgt"));
console.info("<<<<<<<<------------->>>>>>>>>");
let find = list4.find(findFunc); // 返回首个符合条件的元素
console.log(find);
console.log(list4.findLast(findFunc));
console.log(list4.findIndex(findFunc));
console.log(list4.findLastIndex(findFunc));
let list5 = [2,3,56,8,9,12,33,44,22,32];
console.log(list5.sort()); // 即使是数字 他也按照字符串那套比较逻辑进行比较
// 12,2,22,3,32,33,44,56,8,9
console.log(list5.toString());
list5.reverse();
console.log(list5.toString());
let list6 = list5.map(mapFunc); //返回新数组
console.log(list6);
console.log(list4.filter(findFunc)); //返回满足条件的新数组
let reduce = list6.reduce(reduceFunc);
console.log("reduce---->" + reduce);
console.log(list6.reduceRight(reduceFunc));
console.log(list6.every(everyFunc));
console.log(list6.some(everyFunc));
function findFunc(value,index,array){
if(index == 0){
console.log(value);
console.log(index);
console.log(array.toString());
}
return value == 'frgt' || value == 'desaw';
}
function mapFunc(value,index,array){
return value + 1;
}
function reduceFunc(total,value,index,array){
total = total + value;
return total;
}
function everyFunc(value,index,array){
return value > 30;
}
日期
Math
- round() 四舍五入
- pow() 幂
- sqrt() 平方根
- abs() 绝对值
- ceil() 向上取整
- floor() 向下取整
- sin() 计算正弦
- cos() 计算余弦
- min() 查找参数列表中的最小值
- max() 查找参数列表中的最大值
- random() 返回介于>=0 小于1的随机数
console.log("-----------MATH测试------------");
console.log(Math.round(3.1415));
console.log(Math.round(3.632));
console.log(Math.ceil(3.1111));
console.log(Math.floor(3.9999));
console.log(Math.pow(2,8));
console.log(Math.sqrt(25));
console.log(Math.abs(-19));
console.log(Math.min(1,2,3,4,-8));
console.log(Math.random());
条件控制
IF
if (条件){
}else if(条件2){
}else{
}
function ageChangeFunc(){
let age = document.getElementById("age_input").value;
if(age > 50){
document.getElementById("age_message").innerText = '老毕等';
}else if(age <=50 && age > 30){
document.getElementById("age_message").innerText = '中壁灯';
}else{
document.getElementById("age_message").innerText = '小壁灯';
}
}
switch/case
switch 使用 === 来进行比较 值相同且类型形同
switch(表达式){
case n:
代码块;
break;
case n2:
代码块;
break;
……
default:
默认代码块;
}
function sexChangeFunc(){
let sex = document.getElementById("sex_input").value;
switch(sex){
case '男':
document.getElementById("sex_message").innerText = '来了一个英俊潇洒的美男子';
console.log(sex);
break;
case '女':
document.getElementById("sex_message").innerText = '来了一个倾国倾城的小姑娘';
console.log(sex);
break;
case '直升机':
document.getElementById("sex_message").innerText = '来了一架气势汹汹的直升机';
console.log(sex);
break;
default:
document.getElementById("sex_message").innerText = '不知道是个什么性别的怪人';
}
}
循环
for
for(let i=0;i<count;i++){
let li = document.createElement('li');
li.innerText = text;
document.getElementById('loop_test').appendChild(li);
}
for/in
while
do/while
for/of
for (const liNode of childNodes) {
liNode.remove();
}
for/in 和 for/of有什么区别?
- for/in 一般是用来遍历对象的
- for/of 用来遍历可迭代对象 像字符串,数组,set,map等
set集合
定义
- let set1 = new Set([数组]);
let set = new Set();
set.add("张三");
set.add("lisi");
set.add("wangwu");
console.log(set.has("zhangsan"));
console.log(set.keys());
console.log(set.entries());
let keys = set.keys();
for (const key of keys) {
console.log(key);
}
使用
- add() 向集合中增加元素
- 等后面用到的时候再补充
map对象
定义
- let map = new Map();
使用
- push() 向map中添加元素,键可以是对象,值可以是任意类型
解构
- 解构赋值语法将对象属性解包到变量中
let {name,age} = person; // 将person对象中的name,age属性赋值给变量name,age
- 可以解包数组和任何其他可迭代对象
let [l1,l2] = array1;
- 解构不会修改原有的对象
异常
- 语法基本上和java相同
try{
语句……
}catch(err){
处理语句……
}finally{
语句……
}
手动抛出异常
throw 'has a error!'
箭头函数
定义
基本上和java的差不多
let hi = () => "hi!!!!";
let hi2 = (name) => "hi!!!!!" + name;
let hello = () => {
return "hello!!!";
}
let hello2 = (name) => {
return "hello!!!" + name;
}
console.log(hello());
console.log(hello2("hhhhhhhhhh"));
console.log(hi());
console.log(hi2("hhhhhhhhhh"));
this的处理
与常规函数相比,箭头函数对 this 的处理也有所不同,简而言之,使用箭头函数没有对 this 的绑定。
- 在常规函数中,关键字 this 表示调用该函数的对象,可以是窗口、文档、按钮或其他任何东西。
- 对于箭头函数,this 关键字始终表示定义箭头函数的对象。
模块
- 将代码分解成单独的文件,在单独的文件中暴露出数据,在其他文件中直接使用
- 使用export关键字导出数据,import关键字引入
- 在script标签中设置type=moudle
<script type="module">
import message from "./module1.js"
import {host,port,config} from "./module.js"
// 模块使用 其实还行 区分出两种导出的使用方式
console.log("模块-----------------------");
let mess = message(); // 默认导出
console.log(mess.name);
console.log(mess.age);
mess.sayHello("nihao");
console.log(host); // 命名导出
console.log(port);
config.init();
console.log("------------------------");
</script>
命名导出
// 命名导出 可以导出多个变量
const host='http://www.baidu.com';
const port = 3320;
const config = {
host:host,
port:port,
useCache:false,
autoProcess:true,
init:function(){
console.log("配置初始化中........")
}
}
export {host,port,config}
默认导出
// 默认导出,是在一个方法中一次性全部导出
const message = () => {
return {
name:"zhangsan",
age:20,
sex:"男",
sayHello:function(name){
console.log("hello " + name);
},
add:function(v1,v2){
return v1 + v2 + this.age;
}
}
}
// 默认导出 一个对象{}
export default message;
对象与类
对象
定义
- 使用{}可定义一个对象
- 使用new object() 也可以定义一个对象
// 第一种 new Object的方式
var person = new object();
// 添加属性
person.name = 'zhangsan';
// 添加成员方法
person.eat = function(){
alert("eat");
}
// 第二种 直接使用{}进行定义
var person2 = {
name : 'zhangsan',
age : 10,
eat : function(){
}
}
get/set
- get/set关键字类定义getter/setter方法
let person = {
firstName:"zhang",
lastName:"sanfeng",
age:19,
skills:["八卦混元无极掌","闪电五连鞭","纯阳大法"],
// 定义对象中方法
attack:function(index){
console.log(this.firstName + this.lastName + "发动了" + this.skills[index]);
},
// getter setter
// 没啥用啊 你这个对象里又没有权限控制 我直接访问属性不是更加方便?
get getAge(){
return this.age;
},
get name(){
return firstName + " " + lastName;
},
set setAge(age2){
this.age = age2;
}
}
person.attack(1);
// 使用getter setter方法时候像使用属性一样
person.age = 40;
person.setAge = 50;
console.log("age:" + person.getAge);
对象构造器
- 使用对象构造器可以生产多个相同类型的对象
// 对象构造器 用来生成一系列相同的对象
// 有点像是java的构造函数
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
// 定义函数
this.sayHello = function(name){
console.log("hello," + name);
}
};
// 是由构造器构造多个对象
let student1 = new Student('xiaoming',10,'man');
let student2 = new Student('xiaoming2',11,'woman');
let student3 = new Student('xiaoming3',9,'man');
let set = new Set();
set.add(student1);
set.add(student2);
set.add(student3);
for (const temp of set) {
console.log(temp['name']);
temp.sayHello(temp.name);
}
类与继承
- class关键字定义一个类
- constructor关键字定义构造方法
- extends继承一个类
- 能否多继承?不支持
- static定义类变量与类方法
// js类
class Teacher{
// 构造函数
constructor(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
};
// 成员方法 唉 为什么不统一呢?为什么省略掉function关键词呢?
sayHello() {
console.log("hello,my name is " + this.name);
}
isMan(){
return this.sex == 'man';
}
}
// 实例化对象
let teacher = new Teacher('zhangsan',40,'nan');
teacher.sayHello();
console.log(teacher.isMan());
// 类的继承 extends/super
class MathTeacher extends Teacher{
// static 类似于java的静态变量 只能通过类对象进行调用
static schoolName = '中国第九十九中学';
static getSchoolName(){
console.log("欢迎来到光辉伟大的" + MathTeacher.schoolName);
}
constructor(name,age,sex,book){
super(name,age,sex); //调用父类的构造方法
this.book = book;
}
teachMath(){
console.log("请同学们打开课本《" + this.book + "》的第一页");
}
}
// js有多态吗?hhhh
let mt = new MathTeacher('lisi',30,'woman','高等数学');
mt.teachMath();
// 调用类变量
console.log(MathTeacher.schoolName);
MathTeacher.getSchoolName();

浙公网安备 33010602011771号