javascript问题收集(1)

在写js的时候,我们难免会遇到各种各样的坑,有坑不可怕,只要你汲取了经验,就能在以后的项目中避免,这篇博文是我从csdn上看到的,记录下来,以免自己继续踩坑。

对象字面量不能正确解析

{a:3}.a报错,Uncaught SyntaxError: Unexpected token .
解决:

1
({a:3}).a或者({a:1}.a)

原因:

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block. —————–form Mdn:Object literal

大致意思就是,对于对象字面量。语句开头不能用{,因为js解释器会认为这是一个语句块的开始

同理,{ name: "mc", id: 1 }也会报错Uncaught SyntaxError: Unexpected token :(…),改为({ name: "mc", id: 1 })就会正常解析,但稍注意下,{name: "mc"}是不会报错的,它等同于name: "mc",并返回一个字符串"mc"

点操作符

123.toFixed(2)报错,Uncaught SyntaxError: Unexpected token ILLEGAL(…)
解决:

1
2
3
4
(123).toFixed(2) // 123.00
//以下两种也可,但不推荐
123..toFixed(2);
123 .toFixed(2);

原因:
js解释器会把数字后的.当做小数点而不是点操作符。

逗号操作符

问题: 下面代码返回什么?why?

1
2
3
4
5
6
7
8
9
10
var x = 20;
var temp = {
x:40,
foo:function(){
var x = 10;
console.log(this) //window
return this.x
}
};
(temp.foo,temp.foo)(); //20

原因:
逗号操作符会从左到右计算他的操作数。并返回最后一个操作数的值,所以(temp.foo,temp.foo)()等价于var fun = temp.foo;fun(),fun被调用时,this指向window,所以返回20

parseInt传入数字

问题:parseInt传入数字时为什么会有一下输出?

1
2
parseInt(0.000008);	//0
parseInt(0.0000008); //8

原因:
parseInt(arg)时会调用arg.toString()

1
2
(0.000008).toString() //0.000008
(0.0000008).toString() //"8e-7"

https://github.com/creeperyang/blog/issues/2

文章目录
  1. 1. 对象字面量不能正确解析
  2. 2. 点操作符
  3. 3. 逗号操作符
  4. 4. parseInt传入数字