Notes from Eloquent JavaScript

变量类型

  • 表示科学计数法:2.998e8 = 2.998 × 10^8

    正负无穷:Infinity, -Infinity

    出现 arithmetic error 的时候并不会报错,而是得到NaN – not a number

  • string 可用单/双引号和 `,但是 ` 中的 string 可以使用 ${ } 标记 template literal 进行算数运算

    1
    `half of 100 is ${100 / 2}` ==  “half of 100 is 50”

    同其他语言一样可用 \ 来表示 escaping the character

  • 使用 typeof 来表示类型,i.e. typeof 4.5 = ‘number’

  • string 可以直接用 == 或 != , <, > 比较

    NaN != NaN

  • null – 赋值为空 VS undefined – 定义了但还未赋值

    1
    null == undefined, null != 0
  • JS 拥有 type coercion 特性,字符,数字,null(0) 可以一定程度混合运算,混合失败会返回 NaN

    1
    false == 0, false == ""

    如果不需要强制转换,使用 === 或 !===

  • || 会返回左边第一个 true 的东西 (false – null/“”/0/NaN),

    相反,&& 返回左边第一个 false 的东西

JS基础

句尾 ; 可省,单句换行除外

binding – 关键词包括 var/ let/ const

区别:

  1. let 的 scope 更小 ,只在 block 中生效,而 var is function-scoping
  2. var 支持同 scope 重复定义,let 不行

prompt(“ “) function – 网页弹出对话框提示输入,返回输入值 – 已被淘汰……..

console.log() – command line 打印

强制转换 function – 包括 Number(), String(), Boolean()

Function

基于 binding 的 function 定义

1
2
3
4
const square = function(x) {
return x * x;
};
console.log(square(12));

function 如果不 return 特定的值,则默认返回 undefined