javaScript的变量、值与类型

本文主要是奇舞前端特训营的笔记
https://t.75team.com/video前端

变量

变量声明的三种方法mysql

1.var-声明一个变量,可选择将其初始化为一个值sql

- 不支持块级做用域
 - var存在变量提高
console.log(a === undefined) //true
        var a = 10;

2.let-声明一个块级做用域变量,可选择将其初始化一个值浏览器

- 块级做用域
{
    let x = 10;
}
console.log(typeof x); //undefined
- 同一做用域中不容许重复声明
- 暂存死区
- 循环中的let做用域
- 浏览器兼容性

3.const-声明一个只读的常量 绑定的值不能够再次改变ide

类型

ECMAScript语言中全部的值都有一个对应的语言类型。ECMAScript语言类型包括Undefined、Null、Boolean、String、Number和Object。
对语言引擎和开发人员来讲,类型是值的内部特征,它定义了值的行为,以使其区别于其余值this

JavaScript有七种内置类型:spa

空值(null
未定义(undefined
布尔值( boolean
数字(number
字符串(string
对象(object
符号(symbol,ES6中新增)
除对象以外,其余统称为“基本类型”。prototype

Boolean
值:true和false
须要注意:0,"", null, undefined, 会被隐式的转化为false,其余都为truecode

  • 建议采用严格比较,能够经过!!将非boolean转化为booleansqlite

  • 比较操做符总会返回boolean

  • 布尔操做符&&和||不会转化类型

  • &&和||具备短路特性

    console.log(null !== undefined, null == undefined); //true, true
    console.log(1 && 2) //2

Number

  • 数值范围
    整数-2^53~2^53

    超事后会有精度丢失

    小数精度Number.EPSILON
    Infinity, Number.MAX_VALUE, Number.MIN_VALUE

  • 浮点数精度问题
    console.log(0.2+0.4) //0.6000000000000001
    限制精度

    console.log((0.2+0.4).toFixed(2)); // 0.60

String

  • 引号规范和转义
    建议使用单引号

  • 字符串类型转换
    console.log('1'+2, '2'-1);//'12', 1 隐式类型转化
    字符串模版

Object

  • 对象是个引用类型

  • 值类型和包装类型
    包装类型typeof是object

对象的copy

let conf = {
    adapter: 'sqlite',
    db: {
        aqlite: {
            name: 'xxx.sqlite'
        },
        mysql: {
            name: 'xxx',
            username: 'work',
            passwd: '***'
        }
    }
}

// ES6浅拷贝
let copied = Object.assign({}, conf);
copied.adapter = 'mySql';
console.log(conf.adapter); //sqlite
console.log(copied.adapter); //mySql

copied.db.mySql.name = 'yyy.sqlite';
console.log(conf.db.mySql.name); //yyy.sqlite

// 深拷贝
function deepCopy(des, src){
    for( var key in src){
        let prop = src[key];
        if(typeof prop === 'object'){
            des[key] = des[key] || {}; // typeof{} === object
            deepCopy(des[key], src[key]);
        }else {
            des[key] = src[key];
        }
    }
    return des;
}
let deepCopied = deepCopy({}, conf);
deepCopied.db.sqlite.name = 'zzz.sqlite';
// 深拷贝
console.log(deepCopied.db.sqlite.name, conf.db.sqlite.name);//'zzz.sqlite, yyy.sqlite'

对象的类型和构造器

  • new和constructor

    new是一种语法糖

  • prototype

    //原型链
    // __proto__暴力构建原型链
    var a = {x: 1},b = {y: 2}, c = {z: 3};
    b.__proto__ = a;
    c.__proto__ = b;
    console.log(c);
    
    // 使用Object.create(a)构建原型链
    var a = {x: 1};
    var b = Object.create(a);
    b.y = 2;
    var c = Object.create(b);
    c.z = 3;
    console.log(c);
    
    // 使用构造器构建原型链
    function A(){
        this.x = 1;
    }
    function B(){
        this.y = 2;
    }
    B.prototype = new A();
    function C(){
        this.z = 3;
    }
    C.prototype = new B();
    var c = new C();
    console.log(c);
    
    // 三种方式都是构建原型链

    一张图片有助于理解

图片描述

相关文章
相关标签/搜索