不知道为什么只有写在console内才生效
//转换成数字
const num = 12.3456
console.log(num.toFixed(1))
一个综合案例关于购物车界面
//渲染界面,用MAP进行遍历 const str = goodsList.map(item => { const {picture,name,count,spec,price,gift} = item //获取spec再数组内的值,将这个获取的值用join转为字符串用/隔开 const text = Object.values(spec).join('/') //计算小计模块,注意精度问题,因为保留两位小时所以X100再/100 const subTotal = ((price *100 * count)/100).toFixed(2) //处理赠品模块 const gif = gift?gift.split(',').map(item => `<span class="tag">【赠品】${item}</span>` ).join(''):'' return `<div class="item"> <img src=${picture} alt=""> <p class="name">${name} ${gif}</p> <p class="spec">${text}</p> <p class="price">${price.toFixed(2)}</p> <p class="count">x${count}</p> <p class="sub-total">${subTotal}</p> </div>`}).join('') document.querySelector('.list').innerHTML = str //合计模块 const total = goodsList.reduce((prev,item)=> prev+(item.price * 100 * item.count)/100,0) document.querySelector('.amount').innerHTML = total.toFixed(2)
关于构造函数的原型对象
//公共的属性写在构造函数内
function Star (uname,age) {
this.uname = uname
this.age = 18
}
//原型对象内写公共的方法类
//可以用箭头函数简写
//Star.prototype.sing = () => console.log('唱歌')
Star.prototype.sing = function () {console.log('唱歌')}
const ldh = new Star('刘德华',30)
const zxy = new Star('张学友',32)
console.log(ldh.sing()===zxy.sing()) 结果:true
利用原型对象做一个数组的最大值和求和
//自己定义数组扩展方法,任何实例对象都可以使用
//数组是系统隐藏了系统实例化的关键字, new Array
const arr = [1,2,3]
Array.prototype.max = function () {
//this指向了arr这个实例对象
return Math.max(...this)
}
console.log(arr.max())
//用箭头函数写法,匿名函数内的数学函数填写this无效
const arr = [1,2,3]
Array.prototype.max = () => Math.max(...arr)
console.log(arr.max())
Array.prototype.min = () => Math.min(...arr)
console.log([1,3,4,656,3].min())
//求和方法
Array.prototype.sum = function () {
return this.reduce((prev,item) => prev+item,0)
}
console.log(arr.sum())
关于constructor的使用
//空的构造函数
function Star () {
}
Star.prototype = {
//原型对象内指回构造函数
constructor : Star,
sing:function(){
console.log('唱歌')
},
dance:function(){
console.log('跳舞')
},
}
console.log(Star.prototype)
关于原型对象和对象原型以及构造函数的关系
关于原型对象的继承
//设置的一个继承体
const Person = {
eyes : 2,
head : 1
}
//要继承的函数
function man () {
}
//把继承对象给man的原型
man.prototype = Person
//声明man的原型指向他自己
man.prototype.constructor = man
//一定要实例化man,再输出
const test = new man()
console.log(test)
原型继承的改进版,利用了构造函数
function Person () {
this.eyes = 2
this.head =1
}
function Man () {}
//记住,先实例化这个构造函数,因为构造函数的键相同但值可能不相同
Man.prototype = new Person()
//指明从哪里来的
Man.prototype.constructor = Man
const red = new Man()
console.log(red)
function Woman () {}
//子类原型=new 父类()
Woman.prototype = new Person()
Woman.prototype.constructor = Woman
//给原型对象添加一个方法
Woman.prototype.baby = () => console.log('宝贝')
const blue = new Woman()
console.log(blue)
关于原型链的定义
原型链内用instanceof检测是否属于原型链上
//实例化Person给test
const test = new Person()
//test在Person内么?
console.log(test instanceof Person)