Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

点滴记录(javascript) #5

Open
jindada opened this issue Jun 9, 2017 · 4 comments
Open

点滴记录(javascript) #5

jindada opened this issue Jun 9, 2017 · 4 comments

Comments

@jindada
Copy link
Owner

jindada commented Jun 9, 2017

1 . token 是 词法单元的意思

我们经常在看到js的报错信息

ERROR in ./demo.js
Module build failed: SyntaxError: Unexpected token (x:y)

token 就是 词法单元的意思
将代码分解成有意义的代码块,这些代码块成为 词法单元 (token)

var a = 1;  // 分解成 "var","a","=","1",";"

2 . JS常见异常类型

我们一般都是抛出一个自定义的异常,那JS本身常见的异常类型有哪些那?

  • EvalError: raised when an error occurs executing code in eval()
  • RangeError: raised when a numeric variable or parameter is outside of its valid range
  • ReferenceError: raised when de-referencing an invalid reference
  • SyntaxError: raised when a syntax error occurs while parsing code in eval()
  • TypeError: raised when a variable or parameter is not a valid type
  • URIError: raised when encodeURI() or decodeURI() are passed invalid parameters

3 . 阻止冒泡及默认行为

e.preventDefault();
e.stopPropagation();

4 . javascript语言是传值调用

image

5 . 逻辑运算返回的不是 true | false

var a, b = 1, 2;
a && b // 2

逻辑就是测试 真 或 假,真假不是字面量true 或 false
js本身帮你进行了转换,空字串、undefined 0 null false 这5个返回false,其他的都是true

@jindada jindada changed the title 那些不能说的秘密 javascript篇 点滴记录(javascript) Oct 18, 2017
@jindada
Copy link
Owner Author

jindada commented Nov 27, 2017

6 . 取整

~~3.125522 // 3
0|3.125522 // 3
parseInt(3.125522) // 3
Math.floor(3.125522)

~~0.0000000003 // 0
parseInt(0.0000000003) // 3
Math.floor(0.0000000003) // 0

因为 0.0000000003 会使用科学计数法表示为 3e-10,parseInt 会首先把参数转换为字符串,然后解析整数,直到遇到不是数字的值。

parseInt('2017-05-02') // 2017
parseInt('-0') // -0
parseInt(-0) // 0

特殊情况,如果你的返回值是整数(int32),那么可以使用位运算。使用位运算就不需要再去考虑那些非常规的值 NaN、undefined、null 等,这些值都是 0。0也只有唯一的值,不存在 +0 和 -0。

@jindada
Copy link
Owner Author

jindada commented Nov 27, 2017

7 . 解构在数组上面的应用

const {0:a, 2:b, length:l} = ['foo', 'bar', 'baz']
a // 'foo'
b // 'baz'
l // 3
const { length: l, [l-1]: last } = ['foo', 'bar', 'baz']
l // 3
last // 'baz'
const { ...obj } = [1,2,3]
obj // {0: 1, 1: 2, 2: 3}

@jindada
Copy link
Owner Author

jindada commented Nov 28, 2017

@jindada
Copy link
Owner Author

jindada commented Jan 23, 2018

9. 一行代码实现数组求和

var a = [1, 2, 3, 4, 5];
a.reduce((a, b) => a + b)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant