变量类型与计算

变量类型和计算

值类型:

let a = 100;
let b = a;
a = 200;
console.log(b) //100

引用类型

let a = {age:20};
let b = a;
b.age = 21
console.log(a.age) //21

常见值类型

let a //undefined
let s = 'abc';
let n = 100;
let b = true;
let s = Symbol('s');

常见引用类型

let obj = {x:100};
let arr = ['a','b','c'];
let n = null; //特殊引用类型,指针指向为空地址
//特殊引用类型,但不用于存储数据,所以没有“拷贝、复制函数”这一说
function fn() {} 

typeof运算符

// 判断所有值类型
let a;                     typeof a  //'undefined'
let str = 'abc';           typeof str  //'string'
let n = 100;               typeof n  //'number'
let b = true               typeof n  //'boolean'
let s = Symbol('')         typeof s //'symbol'
typeof console.log //'function'
typeof function () //'function'

// 能识别引用类型 (不能在继续识别)
typeof null // 'object'
typeof ['a','b'] // 'object'
typeof {x:100} // 'object'

深拷贝

const obj1 = {
    age: 20,
    name: 'xxxx',
    address: {
        city: 'beijing'
    },
    arr: ['a', 'b', 'c']
}
let obj2 = obj1

obj2.address.city = 'shanghai'
console.log(obj1.address.city)

function deepClone(obj = {}) {
    if (typeof obj !== 'object' || obj == null) {
        return obj
    }
    let result
    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }

    for(let key in obj) {
        if(obj.hasOwnProperty(key)) {

            result[key] = deepCopy(obj[key])
        }
    }
    return result
}

变量计算-类型转换

字符串拼接

let a = 100 + 10 //100
let b = 100 + '10' //'10010'
let c = true + '10' // 'true10'

==运算符

100 == '100' //true
0 == '' // true
0 == false // true
false == '' // true
null == undefined // true

//除了 == null 之外,其他都一律用===,例如:
let obj = {x:100}
if(obj.a == null){}
//相当于:
//if(obj.a === null || obj.a === undefined){}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值