文章目录
- 属性表示方法 obj.name,obj[‘name’]
- 对象枚举(遍历)
- for in 遍历属性名
- Object.getOwnPropertyNames(obj) 返回对象 属性名数组
- Object.keys(obj)/Object.values(obj) es8 返回对象 属性名/属性值 数组
- Object.entries(obj) es8 返回对象 [属性名,属性值] 数组
- hasOwnProperty 判断该对象上有没有该属性
- getOwnPropertyDescriptors es8 该方法返回指定对象所有自身属性的描述对象
- in 判断该对象能不能访问到该属性
- instanceof A instanceof B 看A的原型链 上有没有 B的原型
- 判断一个 变量 是数组还是变量
原生js模仿链式写法
jq链式写法
$(div).css('background',"red").width(100).height(100).html(111)
模仿链式写法
var obj = {
css:function(){
console.log('css')
return this
},
width:function(){
console.log('width')
return this
}
}
obj.css().width();
属性表示方法 obj.name,obj[‘name’]
obj[‘name’] 执行更快 不用隐式转换 更灵活 []
内部必须是字符串
var obj = {
name:"name",
attribute1:{name:'attribute1'},
attribute2:{name:'attribute2'},
attribute3:{name:'attribute3'},
attribute4:{name:'attribute4'},
getAttr:function(i){
return this.['attribute'+i]
}
}
//obj.name -->会隐式的 obj['name']
对象枚举(遍历)
for in 遍历属性名
var obj = {
name:"obj",
age:18,
sex:'male'
}
for(var prop in obj){ //把对象的每个属性名对遍历出来了
obj[prop];
obj.prop;//undefined 把prop 当成属性了
//会隐藏式 的执行 obj['prop']
}
hasOwnProperty
判断对象是否有这个属性
var obj = {
name:"obj",
age:18,
sex:'male',
fun:function(){},
__proto__:{
lastName:"lastName"
}
}
for(var prop in obj){
// console.log(obj[prop]);
// obj 18 male function(){} lastName 会把原型拿出来
// 排除原型的属性
if(obj.hasOwnProperty(prop)){
console.log(obj[prop]) // obj 18 male function(){}
}
}
in
判断这个对象可不可以访问到这个属性
var obj = {
name:"obj",
age:18,
sex:'male',
fun:function(){},
__proto__:{
lastName:"lastName"
}
}
if('name' in obj){
console.log('可以访问到name属性')
}
if('lastName' in obj){
console.log('可以访问到lastName属性')
}
instanceof
A instanceof B //A对象 是不是 B构造函数构造出来的
看 A的原型链上 有没有 B的原型
function Per(){}
var per = new Per();
if(per instanceof Per){//true
console.log( 'per对象 是 Per构造函数构造出来的')
}
if(per instanceof Object){//true
console.log( 'per对象 是 Object构造函数构造出来的')
}
if([] instanceof Object){//true
console.log( '[]对象 是 Object构造函数构造出来的')
}
Object.entries(obj)
返回键值对数组
const obj = {
name:"entries",
data:{datas:"gg"},
arr:[1,2]
}
Object.entries(obj)
创建map集合
const m = new Map(Object.entries(obj))
m.get('name') // "entries"
getOwnPropertyDescriptors
该方法返回指定对象所有自身属性的描述对象
Object.defineProperty() 的属性
const obj = {
name:"entries",
data:{datas:"gg"},
arr:[1,2]
}
Object.getOwnPropertyDescriptors(obj)
value:属性值,默认undefined
writable:值是否可重写,默认false
enumerable:目标属性是否可以被枚举 默认false
configurable:目标属性是否可以被删除或是否可以再次修改特性 默认false
可以用来进行深层次的对象克隆 可以为新对象配置相同的特性
判断一个 变量 是数组还是变量
//有缺陷
//obj仅限于 数组 和 对象
function test(obj){
if(obj.length){
//数组
}else{
//对象
}
}
constructor
[].constructor
var obj = {}
obj.constructor
toString()
function test(obj){
console.log(Object.prototype.toString.call(obj))
}
test([]);// "[object Array]"
test({});// "[object Object]"
test(123);// "[object Number]"
test('fgg');// "[object String]"
instanceof
arr = []
arr intanceof Array //true