对象的扩展
一、json与其他类型之间的转换
// js类型(对象,数组)转换成json格式
JSON.stringify()
// json类型(对象,数组)转换成js格式
JSON.parse()
注意,json格式只有对象和数组
二、Object的扩展之Object.create()
使用:以指定的对象为原型,创建新的对象,并且第二个参数可以为新的对象添加新的属性,并且对这属性进行控制
如:
let a = { // 作为原型的对象
name:"小明",
age:10
}
let b = Object.create(a,{
mobile:{
value:"男",
writable:false, // 该属性是否可修改
configurable:true, // 是否可删除
enumerable:true // 是否可枚举
},
class:{
value:"10",
writable:false, // 该属性是否可修改
configurable:true, // 是否可删除
enumerable:true // 是否可枚举
}
})

假如设置了不可以修改,方法一:可以使用Object.defineProperty()单独进行设置值
// 比如对上面进行设置
Object.defineProperty(b,"class",{
value:9,
writable:true, // 该属性是否可修改
configurable:true, // 是否可删除
enumerable:true // 是否可枚举
})
方法二:使用Obje.defindeProperties的get和set方法进行设置值,并且可以扩展多个属性(上面一次一个)
var c = {
name1:"dd",
name2:"ee"
}
Object.defineProperties(c,{
name:{
// 获取属性值时调用的函数
get: function() {
return this.name1+"-"+this.name2;
},
// 设置属性值时调用的函数
set: function(data){
var arr = data.split("-")
console.log(arr);
this.name1 = arr[0]
this.name2 = arr[1]
}
},
age:{
get:function(){},
set:function(){}
})

get和set方法还可以这样用
var teacher = {
name1:"老师",
age:18,
name2:"是我",
get name(){
return this.name1 + "-"+this.name2
},
set name(data ){
let arr = data.split("-")
this.name1 = arr[0]
this.name2 = arr[1]
},
get bef(){
return "我的名字是"+this.name1+this.name2
}
}

解构赋值
基本用法
let [ a , b , c] = [ '一','二','三' ]
console.log(a); // 一
// 设置默认值,有值被覆盖,没值用默认值
let [ a , b , c="四"] = [ '一','二']
console.log(c); // 四
注意,undefined表示没有值,null也是值
注意,数组是按照对应顺序赋值的,但是对象是按照键值也就是属性名来赋值的,也就是顺序不一样的时候,也会找到正确的值进行赋值
再注意,如果再进行解构之前就已经定义的值,再去解决就会发送错误,解决办法就是再赋值那里外面加一层()
如:
let a = 123;
({a} = {a:456})
console.log(a); // 456
字符串也可以解构,每一个字符对应数组里的一个值
通过Map对象,使用解构的方法使用for of
Map对象的好处就是,可以设置值并且作为for of的对象使用遍历
let a = new Map()
a.set("name","admin")
a.set("password","123456")
console.log(a);
for (const [key,value] of a) {
console.log(key);
console.log(value);
}

字符串模板
let a = 10
let b = 20
let c = `今天赚了${a+b}`
function d() {
return "大傻逼"
}
let e = `你是${d()}`
来源:CSDN
作者:qq_39773416
链接:https://blog.csdn.net/qq_39773416/article/details/104430667