Hiccup
发布于 2021-03-06 / 37 阅读
0
0

JavaScript-变量类型与计算

1.变量类型与计算

1.1.常见值类型

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

1.2.常见引用类型

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

1.3.typeof 运算符

  • 识别所有值类型;

  • 识别函数;

  • 判断是否是引用类型(不可再细分);

判断值类型:

let a;                                          typeof a; // undefined
const str = 'abc';                              typeof str; // string
const n = 100;                                  typeof n; // number
const b = true;                                 typeof b; // boolean
const s = Symbol('s');                          typeof s; // symbol

判断函数:

typeof console.log; // function
typeof function () {}; // function

识别引用类型:

typeof null;            // object
typeof ['a', 'b'];      // object
typeof { x: 100 };      // object

1.4.深拷贝

const obj1 = {
    age: 20,
    name: 'kate',
    address: {
        city: 'beijing'
    },
    arr: ['a', 'b', 'c']
};
const obj2 = deepClone(obj1);
obj2.address.city = 'shanghai';
console.log(obj1.address.city);

function:

function deepClone(obj={}) {
    if (typeof obj !== 'object' || obj == null) {
        // obj 是 null,或者不是对象和数组,直接返回
        return obj;
    }
    let result = {};
    if (obj instanceof Array) {
        result = [];
    }
    for (let key in obj) {
        // 保证 key 不是原型的属性
        if (obj.hasOwnproperty(key)) {
            // 递归调用
            result[key] = deepClone(obj[key]);
        }
    }
    // 返回结果
    return result;
}

1.5.变量计算-类型转换

1.5.1.字符串拼接

const a = 100 + 10;     // 110
const a = 100 + '10';   // '10010'
const a = true + '10';  // 'true10'

1.5.2.==运算符

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

除了 == null 之外,其它都一律用 === ,例如:

const obj = { x: 100 };
if (obj.a == null) {}
// 相当于
if (obj.a === null || obj.a === undefined) {}



评论