数据类型(基本数据类型)
1.Number
2.String
3.Boolean:true false
4. undefined:声明了,未赋值(未定义)
var switch
console.log(switch) //undefined
5.Null:只有null,代表对象,赋值为对象
var whichObject=null //是一个对象
whichObject={name:cxm}
console.log(whichObject)
检测数据类型
1.typeof
var a="111"
console.log(typeof a) // string
var a=111
console.log(typeof a) // number
var a=false
console.log(typeof a) // boolean
var a
console.log(typeof a) // undefined
var a=null
console.log(a) // Object
//结果一定是字符串 string类型
console(typeof typeof a) //typeof typeof a
console.log(typeof a + 100) // number100
console.log(typeof (a + 100)) //number
数据类型转换——转数值
1.Number(变量):强制转换
// string 转数值
var a = '100'
var b = Number(a)
console.log(typeof a, typeof b)
// boolean 转数值
var a = true
var b = Number(a)
console.log(a, b) //true 1,false 0
// null 转数值
var a = null
var b = Number(a)
console.log(a, b) // null,0
// undefined 转数值
var a = undefined
var b = Number(a)
console.log(a, b) // NAN 也是数据类型
2.parseInt(变量)
// string 转数值
var a = '100abc'
var b = parseInt(a)
console.log(a, b) // 100 整数型
3.parseFloat(变量)
// string 转数值
var a = '100.23abc'
var b = parseFloat(a)
console.log(a, b) // 100.23 浮点数型
4.除了加法以外的数学运算
// string 转数值
var a = '100'
console.log(a + 0) // 1000 字符串型
console.log(a - 0) // 100 整数型
数据类型转换——转字符串
1.变量.toString()
// toString() undefined和null无法转换
// Number 转化为字符串
var a = 100
var b = a.toString()
console.log(a, b) // 100,'100'
// undefined 转化为字符串
var a = undefined
var b = a.toString()
console.log(a, b) // 无法转换
// boolean 转化为字符串
var a = false
var b = a.toString()
console.log(a, b) //false,'false'
// null 转化为字符串
var a = null
var b = a.toString()
console.log(a, b) //无法转换
2.String(变量)
// String()所有类型都能转换
// Number 转化为字符串
var a = 100
var b = String(a)
console.log(a, b) // 100,'100'
// undefined 转化为字符串
var a = undefined
var b = String(a)
console.log(a, b) // 'undefined'
// boolean 转化为字符串
var a = false
var b = String(a)
console.log(a, b) // 'false','true'
// null 转化为字符串
var a = null
var b = String(a)
console.log(a, b) // 'null'
3.使用加法运算
// + 只要任意一边是字符串,就会进行字符串拼接
// Number 转化为字符串
var a = 100
var b = a + ''
console.log(a, b) // 100,'100'
// undefined 转化为字符串
var a = undefined
var b = a + ''
console.log(a, b) // undefined,'undefined'
// boolean 转化为字符串
var a = false
var b = a + ''
console.log(a, b) //false,'false'
// null 转化为字符串
var a = null
var b = a + ''
console.log(a, b) //null,'null'
数据类型转换——转布尔型
1.Boolean()
// Boolean() '',0,null,undefined,NaN,这些都是false
// '' 转化为布尔型
var a = ''
var b =Boolean(a,b)
console.log(a, b) // '',false
// 0 转化为布尔型
var a = 0
var b =Boolean(a,b)
console.log(a, b) // 0,false
// null 转化为布尔型
var a = null
var b =Boolean(a,b)
console.log(a, b) // null,false
// undefined 转化为布尔型
var a = undefined
var b =Boolean(a,b)
console.log(a, b) // undefined,false
//NaN 转化为布尔型
var a = NaN
var b =Boolean(a,b)
console.log(a, b) // NaN,false
运算符
1.赋值运算符
// = 是赋值
var a = 1
a = 2
console.log('a', a) // 2
// += -= /= *= 是在自身上再进行+ - / *
var b = 1
b += 1
console.log('b', b) // 2
var c = 1
c -= 1
console.log('c', c) // 0
var d = 4
d /= 2
console.log('d', d) // 2
var e = 1
e *= 4
console.log('e', e) // 4
2.比较运算符
var sum = 100
console.log(sum > 100) //false
console.log(sum >= 100) //true
// == 比较两边 值 是否相等,不管数据类型
// === 比较两边 值和数据类型 是否相等
var a = 1
var b = '1'
console.log(a == b) //true
console.log(a === b) //false
console.log(true == 1) //true
console.log(true === 1) //false
console.log('' == 0) //true
console.log('' === 0) //false
console.log(null == 0) //false
console.log(undefined == 0) //false
// != 不等于 两边 值 是否不等
// !== 不等于 两边 值和数据类型 是否不等
var a = 1
var b = '1'
console.log(a != b) //false
console.log(a !== b) //trie
3.逻辑运算符
// && 两边都为 true ,才会返回true;一边不是,就会返回false
// || 只要一个为true,就会返回true;两边都是false,才会返回false
// ! 取反
var a = true
var b = false
var c = true
var d = false
console.log(a && b) // false
console.log(a && c) //true
console.log(a || b) // true
console.log(b || d) //false
var category = '衣服'
var price = 300
console.log(category === '裤子' && price200) //false
console.log(category === '裤子' || price200) //true
// 特殊:
// 1. !!a ==> 转化为布尔值
var x = '1111'
console.log(!!x) // true
// 2. && || 短路用法 项目中经常用到
var y
console.log(y && y.toString()) // undefined
console.log(111)
var z = ''
console.log(z || '这个家伙很懒,什么都没有留下') // z为空时,输出后面的那句话;不为空时,输出z
4.自增自减运算符
var number = 10
// ++number 先 +1 ,再返回
// document.write(++number) // 11
// console.log(number) //11
// number++ 先返回,再 +1
document.write(number++) // 10
console.log(number) // 11
var sum = 10
// ++sum 先 -1 ,再返回
// document.write(--sum) // 9
// console.log(sum) //9
// sum-- 先返回,再 -1
document.write(sum--) // 10
console.log(sum) // 9
5.三元表达式
// 语法: 条件? 条件为true 的时候执行 : 条件为 false 的时候执行
var age = 13
age > 18 ? console.log('成年了') : console.log('未成年')
// 满200 - 10 ,满100 - 5
var sum = 190
var youhuisum = sum > 200 ? sum - 10 : sum > 100 ? sum - 5 : sum
console.log(youhuisum) //185
条件分支语句
1.if 语句
// if (true) {
// alert('条件成立')
// }
// else (false) {
// alert('条件不成立')
// }
var sum = 200
var youhuiSum
if (sum > 200) {
youhuiSum = sum - 10
} else {
youhuiSum = sum
console.log(youhuiSum)
}
// else if
var sum = 146
var youhuiSum
if (sum > 200) {
youhuiSum = sum - 10
} else if (sum > 100) {
youhuiSum = sum - 5
} else {
youhuiSum = sum
}
console.log(youhuiSum)
2.switch语句
// switch (key) {
// case value:
// break;
// default:
// break;
// }
/*
状态码:
1 未付款
2 已付款
3 已发货
4 已完成
*/
var code = 3
switch (code) {
case 1:
document.write('未付款')
break
case 2:
document.write('已付款')
break
case 3:
document.write('已发货')
break
case 4:
document.write('已完成')
break
// default:
// break
}
循环分支语句
1.while语句
/* while(条件) {
满足条件就执行
}*/
var num = 0
while (num < 10) {
num += 1
console.log(num)
}
// 案例 1 求1-100的和
var num = 1
var sum = 0
while (num <= 100) {
sum += num
num++
}
console.log(sum)
// 案例 2 求一个数字的阶乘 5*4*3*2*1
var a = 1
var b = 1
while (a <= 5) {
b *= a
a++
}
console.log(b)
2.dowhile语句
// do {
// } while (condition);
var n = 0
do {
console.log('li', 0)
n++
} while (n < 10)
// 1-100的和
var a = 1
var sum = 0
do {
sum += a
a++
} while (a <= 100)
console.log(sum)
3.for循环
// for (var i = 0; i < 10; i++) {
// console.log(i)
// }
// 案例
var sum = 0
for (var i = 0; i <= 100; i++) {
sum += i
}
console.log(sum)
// 1000-2000闰年
for (var year = 1000; year <= 2000; year++) {
if (year % 4 === 0) {
console.log('闰年', year)
document.write('闰年' + year + '')
} else {
console.log('元年', year)
document.write('元年' + year + '')
}
}
4.循环控制语句
// continue结束本次循环
for (var n = 0; n < 10; n++) {
if (n === 3) {
continue // 0,1,4,5,6,7,8,9
}
console.log(n)
}
函数(复杂数据类型)
1.初识函数
//function 是一个复杂数据类型
test1() // 调用函数
// 1. 定义函数
// (1) 声明式 能够预解析
function test1() {
console.log('我是test1')
}
// (2)赋值式 不能预解析
var test2 = function () {
console.log('我是test2')
}
test2()
2.函数的参数
// 形参
function test(a, b) {
var drink = a === 1 ? '可乐' : '雪碧'
var ciken = b === 2 ? '鸡米花' : '鸡柳'
console.log('我是test', drink, ciken)
}
// test() // undefined
test(1, 2) // 可乐,鸡米花
3.函数的返回值
// 函数调用本身是个表达式,表达式就应该有个值出现
// return 关键字就是给函数执行完毕一个结果
function add(x, y, z) {
var result = x + y + z
// console.log(result)
return result
}
var res = add(1, 2, 3)
function test(a) {
console.log('传给后端用', a)
}
test(res) //6
/*
return 后面代码不会执行了
*/
4.预解析
console.log(myname) // undefined,预解析
var myname = 'cxm'
console.log(myname) //cxm
// 函数行为 赋值 无预解析
// myFunc() // not a function
var myFunc = function () {
console.log('myFuc')
}
myFunc()
// 声明式 有预解析
test()
function test() {
console.log('test')
}
test()
5.作用域
// 全局作用域 跨越script标签使用
var myname = 'cxm'
// 局部作用域 只有函数能够生成一个局部作用域
function test() {
console.log('test')
var nickname = 'xmxm'
console.log(nickname) //undefined
}
// console.log(nickname) //nickname is not defined
</script>
<script>
console.log(myname)
console.log(test)
//ƒ test() {
// console.log('test')
// }
对象(复杂数据类型)
1.对象的数据类型
// {name : 'cxm'} 对象键值对的集合
// 字面量创建一个对象
var obj = {
name: 'cxm',
age: 20,
location: '安徽',
}
console.log(obj)
// 内置构造函数
var newObj = new Object()
newObj.name = 'cxmm'
newObj.age = 22
console.log(newObj)
2.对象的基本操作
// 1-增
var obj = {}
obj.name = 'cxm'
obj.age = 23
obj.location = '安徽'
console.log(obj)
// 1-删
delete obj.name // delete 关键字
// 1-改
obj.age = 200
// 1-查
document.write('姓名是' + obj.name)
// 2-增
var obj2 = {}
obj2['name'] = 'cxmmmm'
console.log(obj2)
// 2-改
obj2['name'] = 'tuichui'
// 2-查
document.write('姓名是' + obj2['name'])
// 2-删
delete obj2['name'] // delete 关键字
console.log(obj2)
3.对象的遍历
// 数据渲染到页面
var obj = {
name: 'cxm',
age: 23,
location: '安徽',
}
// for循环
for (var i in obj) {
document.write(i + '---' + obj[i] + '<br>')
}
4.不同数据类型存储
// 简单数据类型
var str = 'abcd'
var strp = str
console.log(str, strp)
console.log(str === strp) // true
// 复杂数据类型
var obj = {
name: 'cxm',
age: 23,
}
var obj2 = obj
// obj2.name = 'tuichui' // 原来的对象的name也会被修改
console.log(obj, obj2)
console.log(obj2.name) // tiechui
console.log(obj === obj2) // true
// 存储分为栈和堆
// 栈 :先进先出 简单数据类型
// 堆: 复杂数据类型
var objj1 = { name: 'cxm' }
var objj2 = { name: 'cxm' }
console.log(objj1 == objj2) //false
console.log(objj1 === objj2) //false
var obj = {
name: 'cxm',
age: 23,
}
var obj2 = {}
for (var i in obj) {
obj2[i] = obj[i]
}
obj2.name = 'tuichui' // 原来的对象的name就不会被改变
console.log(obj2)
数组(复杂数据类型)
1.数组的数据类型
// 字面量创建一个数组
var aggArr = [12, 13, 14, 15]
var nameArr = ['cxm', 'zll']
var stuArr = [
{ name: 'cxm', age: 23 },
{ name: 'zll', age: 22 },
]
console.log(aggArr, nameArr, stuArr)
// 内置构造函数
var arr1 = new Array(1, 2, 3, 4)
var arr2 = new Array(10) // empty x 10
console.log(arr1, arr2)
2.数组的基本操作
// length 可读可写
var arr1 = [1, 2, 3, 4]
console.log(arr1.length) // 4
arr1.length = 3
console.log(arr1) // [1,2,3] 只会从后面删
arr1.length = 0 //清空数组
console.log(arr1) // []
// 索引 0,1,2...
var arr2 = ['小曼', '米粒', '大大']
console.log(arr2[1]) // 米粒
// 遍历
var arr3 = [3, 4, 2, 6, 7, 2, 9, 1, 0]
for (var i = 0; i < arr.length; i++) {
console.log(arr3[i])
}
3.冒泡排序
var arr = [4, 3, 2]
/*
交换两个位置
var temp = arr[0]
arr[0] = arr[1]
arr[1] = temp
console.log(arr)*/
for (var m = 0; m < arr.length - 1; m++) {
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
var temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
console.log(arr) // [2,3,4]
}
}
}
4.数组常用方法(对原数组产生影响)
// 对原数组产生影响
// push 数组最后面 追加元素
// 返回值 新数组的长度
var arr1 = [1, 2, 3]
arr1.push(2)
console.log(arr1) // 1,2,3,2
console.log('返回值', arr1.push()) // 4
// pop 数组最后面 删除元素
// 返回值 删除的元素
var arr2 = [1, 4, 5, 8]
var respop = arr2.pop()
console.log(arr2) // 1,4,5
console.log('返回值', respop) //8
// unshift 数组最前面 追加元素
// 返回值 新数组的长度
var arr3 = [1, 8, 9, 3]
var reshift = arr3.unshift(5)
console.log(arr3) // 5,1,8,9,3
console.log('返回值', reshift) //5
//shift 数组最前面 删除元素
// 返回值 删除的元素
var arr4 = [3, 5, 7, 9]
var resift = arr4.shift()
console.log(arr4) // 5,7,9
console.log('返回值', resift) //3
// splice(从第几个开始删【索引号】,删几个)
// splice 从中间任意删除
// 返回值 删除的元素的新数组
var arr5 = [2, 5, 8, 0, 4] // 删除 8
var resplice = arr5.splice(2, 1)
console.log(arr5) // 2,5,0,4
console.log('返回值', resplice) //[8]
// splice(从第几个开始删【索引号】,删几个,增加的内容)
// splice 从中间任意增加
// 返回值 删除的元素的新数组
var arr6 = [2, 5, 8, 4] // 删除 8
var resplices = arr6.splice(2, 1, 'cxm')
console.log(arr6) // 2,5,'cxm',4
console.log('返回值', resplices) //[8]
// resver 倒序
var arr7 = [3, 4, 5, 6]
arr7.reverse()
console.log(arr7)
// sort 排序 接收一个回调函数
var arr8 = [6, 4, 8, 2]
arr8.sort(function (a, v) {
return a - v // 从小到大
// return v - a //从大到小
})
console.log(arr8) // 2,4,6,8
5.数组常用方法(对原数组不产生影响)
// 对原数组不产生影响
// concat(任何数组或者任何数据类型) 拼接数组
var arr = [1, 2, 3]
var arr1 = ['cxm', 'zll']
var res = arr.concat(arr1, 4)
console.log(arr) // [1, 2, 3]
console.log(arr1) // ['cxm', 'zll']
console.log(res) // [1, 2, 3, 'cxm', 'zll',4]
// join 数组 ==> 字符串
var arr2 = [1, 2, 3, 4]
var res1 = arr2.join('-')
console.log(arr2) //[1,2,3,4]
console.log(res1) //1-2-3-4
// slice(从第几个开始截取【索引号】,结束索引) 包含前面的索引,< 后面的索引【不包含后面的】 截取,不影响原数组
var arr3 = ['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'yyy', 'zzz']
var res2 = arr3.slice(3, 6)
console.log(arr3) //['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'yyy', 'zzz']
console.log(res2) //[ 'ddd', 'xxx', 'yyy']
// slice(从第几个开始截取【索引号】到最后) 只有一个参数,从索引号开始到最后 截取,不影响原数组
console.log(arr3.slice(2)) // ['ccc', 'ddd', 'xxx', 'yyy', 'zzz']
// slice() 不传参数 不截取,不改变 不影响原数组
console.log(arr3.slice()) //['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'yyy', 'zzz'] 数组的复制
// indexOf(查找的元素,从索引号开始查) 返回我们要查找的类型索引值
// 返回 -1 找不到元素
// 返回 索引号 能找到元素
var arr4 = ['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'zzz']
var res4 = arr4.indexOf('ccc', 1)
console.log(res4) // 1
console.log(arr4.indexOf('www')) //-1
// lastIndexOf 从后面开始查找
// 返回 -1 找不到元素
// 返回 索引号 能找到元素
var arr5 = ['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'zzz']
var res5 = arr5.lastIndexOf('ddd')
console.log(res5) // 1
console.log(arr5.lastIndexOf('www')) //-1
6.数组去重
// 1-方法 indexOf
var arr = [1, 2, 4, 5, 2, 5, 6, 8, 6, 1]
var arr1 = []
for (var i = 0; i < arr.length; i++) {
if (arr1.indexOf(arr[i]) === -1) {
arr1.push(arr[i])
}
}
console.log(arr) // [1, 2, 4, 5, 2, 5, 6, 8, 6, 1]
console.log(arr1) //[1, 2, 4, 5, 6, 8]
// 2-方法 利用对象
var arr2 = [1, 2, 4, 5, 2, 5, 6, 8, 6, 1]
var obj = {}
for (var i = 0; i < arr2.length; i++) {
obj[arr[i]] = 'aa'
}
console.log(obj) //{1: 'aa', 2: 'aa', 4: 'aa', 5: 'aa', 6: 'aa', 8: 'aa'}
var arr3 = []
for (var i in obj) {
arr3.push(i - 0)
}
console.log(arr3) // [1, 2, 4, 5, 6, 8]
// 3-方法 set方法
var arr4 = [1, 2, 4, 5, 2, 5, 6, 8, 6, 1]
var set1 = new Set(arr4)
console.log(set1) //Set(6) {1, 2, 4, 5, 6,1}
// 把 Set 转换为数组 Array.from
var arr5 = Array.from(set1)
console.log(arr5) //[1, 2, 4, 5, 6, 8]
7.数组常用方法(3)
// foreach 遍历
var arr = ['aaa', 'bbb', 'ccc', 'ddd', 'xxx', 'zzz']
// 回调函数(每一项,索引值,原数组)
arr.forEach(function (item, index) {
console.log(item, index) //aaa 0 ;bbb 1 ;ccc 2;ddd 3;xxx 4;zzz 5
})
// arr.forEach(function (item, index, arr) {
// console.log(item, index, arr)
// })
// map 映射
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8]
var res = arr1.map(function (item) {
return item
})
console.log(res) // [1, 2, 3, 4, 5, 6, 7, 8]
// filter 过滤 return 返回的是 true 就会加入新数组
// 可以找到满足条件的所有项
var arr2 = [1, 2, 3, 4, 5, 6, 7, 8]
var res1 = arr2.filter(function (item) {
return item > 4
})
console.log(res1) // [5, 6, 7, 8]
// filter 过滤数组里的对象
var arr3 = [
{
name: 'aaa',
price: 200,
},
{
name: 'bbb',
price: 100,
},
{
name: 'ccc',
price: 300,
},
]
var res2 = arr3.filter(function (item) {
return item.price > 100
})
console.log(res2) // [{ name: 'ccc', price: 300,}]
// every 每一个
// 每一项 都 满足条件 true
// 有一项 不 满足条件 false
// 如果第一项不满足 直接 false
var arr4 = [80, 89, 99, 77, 92]
var res3 = arr4.every(function (item) {
return item > 85
})
console.log(res3) // false
// some 只要一个条件满足 就是 true
// 都不满足 false
var arr5 = [80, 89, 99, 77, 92]
var res4 = arr4.some(function (item) {
return item > 85
})
console.log(res4) // true
// find 找到满足的条件的第一项
var arr6 = [
{
name: 'aaa',
price: 200,
},
{
name: 'bbb',
price: 100,
},
{
name: 'ccc',
price: 100,
},
]
var res5 = arr6.find(function (item) {
return item.price === 100
})
console.log(res5) //[ { name: 'bbb',price: 100,}]
// reduce(回调函数,初始值) 累加
// prev 上一次的结果 item 每一项
var arr7 = [80, 89, 99, 77, 92]
var res6 = arr7.reduce(function (prev, item) {
return prev + item
}, 0)
console.log(res6) // 437
字符串
1.字符串的基本操作
var str1 = 'hello'
console.log(str1) //hello
// length 只读
console.log(str1.length) //5
// 索引【下标】 只读
console.log(str1[1]) //e
// 遍历
for (var i = 0; i < str1.length; i++) {
console.log(i, str1[i]) // 0 'h' 1 'e' 2 'l' 3 'l' 4 '0'
}
var str2 = new String('hello')
console.log(str2) //String {'hello'}
// 案例:统计字母出现的次数
var str3 = 'abcabcab'
var obj = {}
for (var i = 0; i < str3.length; i++) {
var key = str3[i]
if (obj[key] === undefined) {
obj[key] = 1
} else {
obj[key]++
}
}
console.log(obj) //{a: 3, b: 3, c: 2}
2.字符串常用方法
var str = 'Kerwin'
// chartAt(索引) 传入索引--返回索引对应的字符
var str1 = str.charAt(1)
console.log(str) //kerwin
console.log(str1) //e
// chartCodeAt(索引) 传入索引--返回索引对应的字符编码
var str2 = str.charCodeAt(1)
console.log(str) //kerwin
console.log(str2) //101
//toUpperCase()--改为大写 toLowerCase()--改为小写
console.log(str.toUpperCase()) //KERWIN
console.log(str.toLowerCase()) //kerwin
// 截取 substr(开始索引,截取长度) substring(开始索引,结束索引)--包括前,不包括后 slice(开始索引,结束索引)--包括前,不包括后
var str3 = 'hEllO'
var str4 = str3.substr(1, 2)
var str5 = str3.substring(1, 2)
var str6 = str3.slice(1, 2)
console.log(str4) // El
console.log(str5) //E
console.log(str6) //E
//replace 替换 只替换第一个 后面使用正则
console.log(str.replace('e', '*')) //K*rwin
// split 分割(把字符串分割为数组)
console.log(str.split('')) //['K', 'e', 'r', 'w', 'i', 'n']
// indexOf(查找的字符串,索引号【从哪开始查】) lastIndexOf
// 找到返回字符串索引位置
// 找不到返回 -1
var str7 = 'abcdef'
console.log(str7.indexOf('d')) // 3
console.log(str7.lastIndexOf('d')) // 3
// concat 连接字符串
console.log(str.concat(str3)) //KerwinhEllO
// trim 去掉首尾空格
// trimStart() trimLeft() 去掉首空格
// trimEnd() trimRight() 去掉尾空格
var str8 = ' Hello World '
console.log('|' + str8 + '|') //| Hello World |
console.log('|' + str8.trim() + '|') //|Hello World|
console.log('|' + str8.trimStart() + '|') //|Hello World |
console.log('|' + str8.trimEnd() + '|') //| Hello World|
3.模糊查询
// 模糊查询
var arr = ['aaa', 'abc', 'bbc', 'ccd', 'ddd', 'bcd']
// 数组 filter 字符串 indexOf
var input = prompt('请输入查询的内容')
var res = arr.filter(function (item) {
return item.indexOf(input) !== -1
})
console.log(res) //['abc', 'bbc', 'bcd']
4.json格式字符串
// 字符串 ==> 对象
// {"key":111,"key":"111"}
var str = '{"name":"cxm","age":100}'
console.log(str) //{"name":"cxm","age":100}
var obj = JSON.parse(str)
console.log(obj) //{name: 'cxm', age: 100}
// 前端==>后端
var obj1 = { name: 'cxm', age: 100 }
console.log(obj1) //{name: 'cxm', age: 100}
var str1 = JSON.stringify(obj1)
console.log(str1) //{"name":"cxm","age":100}
5.模板字符串
// es6 `` ${}
var myhtml = `<li>111</li><li>222</li>`
document.write(myhtml)
var myname = 'cxm'
var myhtml2 = `my name is ${myname}`
document.write(myhtml2)
数字
1.数字常用方法
时间对象
1.时间对象
var date = new Date()
console.log(date) //Mon Sep 05 2022 15:55:43 GMT+0800 (中国标准时间)
// new Date 传参
// 1 个参数 毫秒数
var date1 = new Date(1000)
console.log(date1) //Thu Jan 01 1970 08:00:01 GMT+0800
// 2 个参数 3个参数
var date2 = new Date(2023, 0, 3, 10, 10, 10)
console.log(date2) //Tue Jan 03 2023 10:10:10 GMT+0800
2.时间对象常用方法
var date = new Date()
// getFullYear()
console.log(date.getFullYear()) //2022
// getMonth() 0-11 ==> 1-12
console.log(date.getMonth()) //8
// getDate()
console.log(date.getDate()) //5
// getDay 周日 0 周一~周六 1-6
console.log(date.getDay()) //1
// getHours
console.log(date.getHours()) // 时
console.log(date.getMinutes()) // 分
console.log(date.getMinutes()) // 秒
// getTime() 时间戳 距离1970年的微秒
console.log(date.getTime()) //1662366046797
// --------设置 set-----
var date1 = new Date()
date1.setFullYear(2025)
date1.setMonth(5)
date1.setDate(25)
date1.setHours(35)
console.log(date1) //Thu Jun 26 2025 11:25:55 GMT+0800 (中国标准时间)
date1.setTime(1662366398198)
console.log(date1)
BOM(浏览器对象模型)
1.本地存储
// 存---只能存字符串
btn.onclick = function () {
console.log(localStorage.setItem('name', 'cxm')) //存
}
btn2.onclick = function () {
console.log(localStorage.getItem('name')) //取
}
btn3.onclick = function () {
console.log(localStorage.removeItem('name')) //删
}
// 永久存储:localStorage
// 临时存储:sessionStorage 关闭页面丢失
2.记住用户名
// 先获取用户名、密码
var uservalue = localStorage.getItem('username')
var passvalue = localStorage.getItem('password')
if (uservalue && passvalue) {
username.value = uservalue
password.value = passvalue
}
login.onclick = function () {
console.log(username.value, password.value)
localStorage.setItem('username', username.value)
localStorage.setItem('password', password.value)
}
DOM(文档对象模型)
1.渲染页面
<style>
li {
overflow: hidden;
}
li img {
width: 150px;
height: 150px;
float: left;
}
</style>
<script>
var firmList = [
{
url: 'https://pic.maizuo.com/usr/movie/ddd98af15ecd1336e87c054d366f9761.jpg?x-oss-process=image/quality,Q_70',
title: '世间有她',
grade: '7.5',
},
{
url: 'https://pic.maizuo.com/usr/movie/ddd98af15ecd1336e87c054d366f9761.jpg?x-oss-process=image/quality,Q_70',
title: '世间有她',
grade: '7.5',
},
{
url: 'https://pic.maizuo.com/usr/movie/ddd98af15ecd1336e87c054d366f9761.jpg?x-oss-process=image/quality,Q_70',
title: '世间有她',
grade: '7.5',
},
]
var firmItems = firmList.map(function (item) {
return `<li>-
<img src="${item.url}" alt="">
<h3>${item.title}</h3>
<p>${item.grade}</p>
`
})
console.log(firmItems.join(''))
document.write(firmItems)
</script>
this指向
1.this指向
// this 关键字
// this 谁调用我,this就指向谁(es6箭头函数)
// 全局
function test() {
console.log(this) // window
}
test()
setTimeout(() => {
console.log(this) // window
}, 2000)
// 对象
var obj = {
name: 'cxm',
test: function () {
console.log(this) //{name: 'cxm', test: ƒ}
},
}
obj.test()
2.改变this指向
// call apply bind
var obj1 = {
name: 'cxm',
test: function (a, b, c) {
console.log(this.name) //{name: 'cxm', test: ƒ}
console.log('参数', a, b, c)
},
}
var obj2 = {
name: 'zll',
test: function () {
console.log(this.name) //{name: 'cxm', test: ƒ}
},
}
// obj1.test()
// obj2.test()
// call 执行函数,并改变this执行为函数的第一个参数
// 支持多个参数
obj1.test.call(obj2, 1, 2, 3)
// apply 执行函数,并改变this执行为函数的第一个参数
// 支持两个参数,第二个参数为数组
obj1.test.apply(obj2, [1, 2, 3])
// bind 改变this指向为函数的第一个参数,不会自动执行函数
// 支持多个参数
var fun1 = obj1.test.bind(obj2, 1, 2, 3)
console.log(fun1)
fun1()
ES6
1.ES6定义变量
// var 可以访问到a
console.log(a) //undefind
var a = 100
console.log(a) //100
// let
// console.log(b) // Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 200
console.log(b) //200
/*
let 与 var 的区别
1、必须先定义再使用
2、变量重名,可以检查重名问题
3、块级作用域 {}
*/
// const
console.log(c) //Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 300
console.log(c) //200
/*
let 和 const 的区别
1、let 定义变量
let name="cxm"
name="zll" √
2、 const定义常量
const name="cxm"
name="zll" x
*/
2.箭头函数
var test = () => {
console.log(111) // 111
}
test()
/*
箭头函数特点:
1、(只有一个参数的时候)可以省略
2、{}可以省略,只有一句代码 / 只有返回值的时候
3、没有 arguments
4、箭头函数没有 this,箭头函数this是父级作用域的
*/
var a = function () {
console.log(arguments) //Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
}
a(1, 2, 3)
var b = () => {
console.log(arguments) //arguments is not defined
}
b(1, 2, 3)
3.解构赋值
// 快速的从对象和数组中获取里面的成员
var arr = ['xm', 'cxm', 'zll']
let [x, y, z] = arr
console.log(x, y, z) //xm cxm zll
// 三维数组
var arr2 = [1, 2, [3, 4, [5]]]
// console.log(arr2[2][2]) // [5]
var [a, b, [c, d, [e]]] = arr2
console.log(e) // [5]
4.展开运算符
// ...展开数组
var a = [1, 2, 3]
var b = [4, 5, 6]
var c = [...a, ...b]
console.log(c) //Array(6)
// ...复制
var x = [1, 2, 3]
var y = [...x]
console.log(y) // [1,2,3]
console.log(x === y) //false
// ...参数-实参-形参
var test = (...arr) => {
console.log(arr)
}
test(1, 2, 3, 4, 5) //[1,2,3,4,5]
// ...伪数组转换
function test1() {
var arr = [...arguments]
console.log(arr) //[1,2,3,4,5]
}
test1(1, 2, 3, 4, 5)
// ...对象
var a2 = { one: 1, two: 2, th: 3 }
var b2 = { on: 1, tw: 2, the: 3 }
var c2 = { ...a2, ...b2 }
console.log(c2) //{one: 1, two: 2, th: 3, on: 1, tw: 2, …}
5.模块化语法
// 导出(./module/A.js)
export { A, AA, A5 }
(01.html)
<script type="module">
/*
webpack
模块化
1、私密不漏
2、重名不怕
3、依赖不乱
*/
// 导入
import { A, AA, A5 } from './module/A.js'
A()
AA()
A5()
</script>
6.class
class CreateObj {
// 构造器函数
constructor(name) {
this.name = name;
}
}
var obj = new CreateObj("cxm");
console.log(obj); //CreateObj {name: 'cxm'}
7.继承
function Person(name, age) {
this.name = name;
this.age = age;
}
// 构造函数继承 ---> 只能继承属性,不能继承原型
Person.prototype.say = function () {
console.log(this.name, "hello");
};
function Student(name, age, grade) {
Person.call(this, name, age); // 继承(call 改变this指向)
this.grade = grade;
}
// 原型函数继承
Student.prototype = new Person(); // 挂在原型上
// 在基础上增加方法
Student.prototype.like = function () {
console.log(this.name, this.grade);
};
// 在基础上覆盖方法
Student.prototype.say = function () {
console.log(this.name, this.grade);
console.log(this.name, "您好");
};
var obj = new Student("cxm", 100, 100);
console.log(obj); //Student age:100 grade:100 name:'cxm'
obj.say();
8.es6继承
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log(this.name, "hello"); // cxm hello
}
}
// 子类
// extends 原型继承
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 语法糖,直接改变this指向 // == Person.call(this, name, age)
this.grade = grade;
}
}
var obj = new Student();
console.log(obj);
前后端交互
1.ajax
// ajax ===async javascript and xml(闭合标签)
// json.parse()
// 1.创建 XHR new XMLHttpRequest()
var xhr = new XMLHttpRequest();
console.log(xhr);
// 2.配置 open(请求方式,请求地址,是否异步)
xhr.open(
"GET",
// localhost 本机域名 127.0.0.12 本机ip
"http://127.0.0.1:5500/16%E5%89%8D%E5%90%8E%E7%AB%AF%E4%BA%A4%E4%BA%92/1.txt"
);
// 3.send
xhr.send(); // 没有send()就没有readyState==4
// 4.接收数据,注册一个事件
xhr.onreadystatechange = function () {
console.log(xhr.readyState);
if (xhr.readyState == 4) {
console.log("数据解析完成", xhr.responseText);
}
};
2.ajax同步异步
// ajax ===async javascript and xml(闭合标签)
// json.parse()
// 1.创建 XHR new XMLHttpRequest()
var xhr = new XMLHttpRequest();
console.log(xhr);
下···
// 2.配置 open(请求方式,请求地址,是否异步)
// true 表示异步请求
// false 表示同步请求
xhr.open(
"GET",
// localhost 本机域名 127.0.0.12 本机ip
"http://127.0.0.1:5500/16%E5%89%8D%E5%90%8E%E7%AB%AF%E4%BA%A4%E4%BA%92/1.txt",
true
);
// 3.send
xhr.send(); // 没有send()就没有readyState==4
// 4.接收数据,注册一个事件
xhr.onload = function () {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
};
console.log(111111111);
3.promise基础语法
// promise 构造函数
var q = new Promise(function (resolve, reject) {
// 异步
setTimeout(() => {
// 成功兑现承诺
resolve();
// 失败兑现承诺
// reject()
}, 2000);
});
// pending 执行中
// fulfilled 当调用resolve(成功),状态:pending=>fulfilled
// reject 当调用reject(失败),状态:pending=>rejected
// q是promise对象
q.then(function (res) {
// 兑现承诺,这个函数被执行
console.log("success", res);
}).catch(function (err) {
// 拒绝承诺,这个函数被执行
console.log("fail", err);
});
4.封装ajax
function pajax(options) {
var a = new Promise((resolve, reject) => {
ajax({
...options,
success(res) {
resolve(res);
},
error(err) {
reject(err);
},
});
});
}
pajax()
.then(() => {})
.catch((err) => {
console.log(err);
});
5.async和await
async function test(params) {
// await 同步代码 promise对象
await console.log(111);
console.log(222);
}
test();
6.闭包
/*
函数内部返回一个函数,被外界所引用
这个内部函数就不会被销毁回收
内部函数所用到的外部函数的变量也不会被销毁
*/
function outer() {
var name = "cxm";
return function () {
return name + "111";
};
}
var func = outer();
console.log(func());
/*
优点:让临时变量永驻内存
缺点:内存泄漏 func=null
*/