js怪癖

偶然看见,问问那些不注重细节的童鞋,哈哈哈~

问题:为什么 ++[[]][+[]]+[+[]] = 10?

原理:js的隐式类型转换

参考链接:http://justjavac.com/javascript/2012/12/20/object-plus-object.html

注意:js运算符优先级

运算符 描述
. [] () 字段访问、数组下标、函数调用以及表达式分组
++ -- - ~ ! delete new typeof void 一元运算符、返回数据类型、对象创建、未定义值
* / % 乘法、除法、取模
+ - + 加法、减法、字符串连接
<< >> >>> 移位
< <= > >= instanceof 小于、小于等于、大于、大于等于、instanceof
== != === !== 等于、不等于、严格相等、非严格相等
& 按位与
^ 按位异或
| 按位或
&& 逻辑与
|| 逻辑或
?: 条件
= oP= 赋值、运算赋值
, 多重求值

知识点:

1.在javascript中,一共有两种类型的值:

原始值:undefined,null,boolean,string,number

对象值(objects)

2.通过ToNumber()将值转换为数字

参数 结果
undefined NaN
null +0
boolean true被转换为1,false转换为+0
number 无需转换
string 由字符串解析为数字。例如,"324"被转换为324
3. 通过ToString()将值转换为字符串

参数 结果
undefined "undefined"
null "null"
boolean "true" 或者 "false"
number 数字作为字符串。比如,"1.765"
string 无需转换
4. 通过 ToPrimitive() 将值转换为原始值 会进行下面的操作来转换 :

ToPrimitive(inputPreferredType?)

  1. 如果 input 是个原始值,则直接返回它。

  2. 否则,如果 input 是一个对象。则调用 obj.valueOf() 方法。 如果返回值是一个原始值,则返回这个原始值。

  3. 否则,调用 obj.toString() 方法。 如果返回值是一个原始值,则返回这个原始值。

  4. 否则,抛出 TypeError 异常。

5.加法 内部的操作步骤是这样的:

value1 + value2
  1. 将两个操作数转换为原始值 (以下是数学表示法的伪代码,不是可以运行的 JavaScript 代码):

     prim1 := ToPrimitive(value1)
     prim2 := ToPrimitive(value2)
    

    PreferredType 被省略,因此 Date 类型的值采用 String,其他类型的值采用 Number

  2. 如果 prim1 或者 prim2 中的任意一个为字符串,则将另外一个也转换成字符串,然后返回两个字符串连接操作后的结果。

  3. 否则,将 prim1 和 prim2 都转换为数字类型,返回他们的和。

*****************************************************************************************************************************************************************************************
问题:1.2 == true 是的结果是true还是false?
7.2.12 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is the same as Type(y), then
	Return the result of performing Strict Equality Comparison x === y.
4. If x is null and y is undefined, return true.
5. If x is undefined and y is null, return true.
6. If Type(x) is Number and Type(y) is String,
	return the result of the comparison x == ToNumber(y).
7. If Type(x) is String and Type(y) is Number,
	return the result of the comparison ToNumber(x) == y.
8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
	return the result of the comparison x == ToPrimitive(y).
11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
	return the result of the comparison ToPrimitive(x) == y.
12. Return false.
总结几句就是:
非Number 转换为Number 来比较(Boolean转成0或者1,String转成对应Number值),对象类型转换为原始类型来处理

猜你喜欢

转载自blog.csdn.net/panying0903/article/details/72842393