JavaScript笔记-1

2019-03-20  本文已影响0人  蚂蚁踩死我

字面量、常量、变量、数据类型

变量和常量

    let currentTempC ;  //ES6 声明变量,不初始化值
    var currentTempC = 5 ;  //ES5 声明变量,初始化值为数字5

    // 同时声明多个变量
    let targetTempC, 
        room1 = "conference_room_a",
        room2 = "lobby";

变量、常量选择

标识符命名

习惯规范

字面量

字面量是一种创建值得方式

基本类型和对象

JavaScript中只有个这两种值

数字

字符串

-表示
    * 单引号 ''
    * 双引号 ""
    * 重音符 `` ES6引入,为了启用模板字符串

转义

特殊字符

除了转义引号,反斜杠还能表示不可打印的字符

模板字符串(字符串插值)

ES6新的字符串连接机制
let a = 10.5 ;

//  ES5字符串连接
const message1 = "The number is " + a;  //"The number is 10.5"

// ES6字符串连接
const message2 = `The number is ${a}`;  //"The number is 10.5"

// 花括号内部可以使用任意表达式
const message3 = `THe number is ${a/2}`;    //"The number is 5.25"

多行字符串

let arr = new Array ;
        // 单双引号换行需要使用转义,会包含line2前面的缩进
        alert(
            arr[0] = "line1\n\
            line2"
        )
        //重音符不需要,也会包含lin2前面的缩进
        alert(
            arr[1] = `line1
        line2`
        )
        //不管使用'、"、` 这样都会包含缩进空格
        alert(
            arr[2] = 'line1\n\
                line2\n\
            line3'
        )
        //不想包含缩进空格写法 ``,'', ""都一样
        alert(
            arr[3] = `line1\n` +
                    `line2\n` + 
                `line3` 
        )

数字用作字符串

当需要数字时,字符串会转换为数字
当需要字符串时,数字会转换为字符串

布尔型

符号(ES6)

代表唯一的标志,独一无二,不会匹配其他任何符号
需要唯一的标识符避免跟其他标识符混淆,使用符号
 const RED = Symbol() ;
        //可传入一些描述信息
        const BLUE = Symbol("adf") ;
        // 每个符号都是唯一
        alert(RED===BLUE) ;//flase

null、undefined

对象

本质上对象是一个容器,容器得内容可以改变(同一对象可以拥有不同的内容)
let obj = new Object ;
const SIZE = Symbol() ;

//添加color属性
obj.color = "yellow" ;
//添加SIZE符号属性
obj[SIZE] = 998 ;
//添加SIZE属性,有别于上一条
obj.SIZE = 0 ;

console.log(obj.SIZE) ; //0
console.log(obj[SIZE]) ; //998
delete obj.color ; //obj得color属性被删除。

Number, String, Boolean对象

这些对象两种用途

  1. 存储特殊值,例如:Number.INFINITY

  2. 以函数形式提供某些功能,例如.toUpperCase()

    const s = "hello";
    s.toUpperCase() ;        //"HELLO"
    

PS:下面是流程图,简书不支持

graph TB

id1((创建常量 s))-->初始化为基本的字符串类型
初始化为基本的字符串类型-->创建临时String对象
创建临时String对象-->调用对象的toUpperCase函数
调用对象的toUpperCase函数-->id2(删除临时对象)
 

数组

拖尾逗号

//arr第三个元素后的逗号,即是拖尾逗号
const arr = [
  "a",
  "b",
  "c",
]
  1. 早期版本浏览器,拖尾逗号会产生错误

  2. JSON不允许存在拖尾逗号

    所以尽量避免这种写法

日期

//创建当前日期对象
const now = new Date() ;

//创建指定日期对象1992年12月24日
const time1 = new Date(1992, 12, 24) ;

//创建指定日期和时间的对象1992年12月24日21点30分
const time2 = new Date(1992, 12, 24, 21, 30)

正则表达式

映射和集合

数据类型转换

转换成数字

  1. 使用Number对象的构造方法

    const numStr = "3.3" ;
    const num = Number(numStr) ; //不是Number对象的实例
    
  2. 使用内置函数parseIntparseFloat,可以指定基数

  3. 布尔值转换为数字

    const a = true ;
    const b = a?1:0 ;
    
  4. 日期使用valueOf()方法得到的是1970年1月1日0点到当前时间毫秒数

转换成字符串

任何对象都有toString()方法,除了用在数字数组上,其他使用上都不是很实用

转换成布尔类型

  1. 使用两次"not"操作符!

  2. Boolean对象构造方法没有new关键字

    const n = 0 ;
    const bool1 = !!n ;
    const bool2 = Boolean(n);
    
上一篇 下一篇

猜你喜欢

热点阅读