隐式类型转换部分
// 题1:
var a = false + 1; //因为有‘+’, false隐式类型转换为0,true会转换为1;所以是var a = 0 + 1;
console.log(a); //输出1
// 题2:
var b = false == 1; // == 是比较运算符,false转换为0 ,0==1 为假false;
console.log(b); //输出false
// 题3:
if(typeof(c) && (-true) + (+undefined) + ''){ //虽然c没有定义,但是不报错,typeof(c)输出字符串类型的 'undefined','undefined'不是空字符串,所以转换为真true;
// 因为typeof(c)返回true才继续往后看&&后面的部分,若是返回false就直接走else部分了;
// 因为&&后面部分是用+连接的,所以每一部分也会被隐式类型转换为 数字类型;
// -true 转为-1; +undefined 转为 NaN,NaN也是数字类型,因为undefined转不成数字;
// 所以 -1 + NaN 等于 数字NaN; NaN + '' 等于 'NaN' 字符串类型的'NaN',任何数据类型 + '字符串' 都有转为字符串进行拼接;
// ''空字符串转换为布尔的时候是false,'abc'转布尔是true;
// 所以是 if('undefined' && 'NaN'){} 'undefined' && 'NaN'是 true && true
console.log('题3通过了'); //输出 通过了
}else{
console.log('题3未通过');
}
// console.log(d); 会报错:d is not defined; 没有定义的变量,直接引用会报错;
// console.log(typeof(d)); 不会报错,打印undefined; 而且输出的undefined是字符串类型的undefined;
// 题4:
if(1 + 5 * '3' === 16){ //计算运算符也是 乘除优先于加减,所以先算乘除;
// 除了加号运算符(数字和字符串相加,无论数字位置,数字都会为转为字符串,然后字符串拼接;)
// 其他运算符(减、乘、除、大于、小于)计算数字和字符串,都是字符串转为数字,进行数字运算;
// 所以 1 + 5 * '3' => 1 + 5 * 3 =>1 + 15 => 16,且是数字类型的16 === 16 是true;
console.log('题4通过了'); //输出 通过了
}else{
console.log('题4未通过');
}
// 题5:
console.log(!!' ' + !!'' - !!false || '未通过'); //输出 1
// ' '空格转换为真true, !!' ' 为真true; !!'' => ''空字符串隐式转换为布尔false => !!'' => !!false => false;
// !!' ' + !!'' - !!false || '未通过' => true + false - false || '未通过' => 1 + 0 - 0 ||'未通过'
// 1 || '未通过' => || 前是1 为真,不再往下走了,打印1
console.log( 1 || '未通过'); //输出 1
console.log( 0 || '未通过'); //输出 '未通过'
console.log(1 && '通过'); //输出 '通过'
console.log(0 && '通过'); //输出 '0'
// && 且运算是&&前是真往后走&&后部分,&&前是假 直接结束运算,返回假;
// || 或运算是 ||前是假往后走||后的部分,||前是真 直接结束运算,返回真;
// 题6:
window.a || (window.a = '1'); //()运算的优先级最高,比|| 和赋值都要高;
// 先算()里,把1 赋值给window.a => 然后走||运算,||前的window.a 为1,||前为true,结束这行 走下一行;
console.log(window.a); //输出1
// 虽然,window.b 返回false
// 题1:
var fn =(
function test1(){
return 1;
}, //,逗号分隔符,只会返回最后一位
function test2(){
return '2';
}
)(); //后面这个()是立即执行
// var num =(1,2); console.log(num); => 打印2 ','逗号是个运算符,只会返回最后一位;
// 所以fn返回最后一位,function test2(){return '2';}; ()立即执行后,返回'2',typeof('2') => string
console.log(typeof(fn)); // 打印string
// 题2:
var a = 10;
if(function b(){}){ //null、undefined、''、0、false 转布尔的时候为假 false
// function b(){} 这是函数声明, (function b(){})用()括起来后变成表达式了,像(1<2)就是表达式,表达式忽略函数名b
a += typeof(b); //b 被忽略了,所以不存在了 typeof(不存在、没被定义的) 返回字符串'undefined'
// a += b => a = a + b;
// a += typeof(b) => a= a + 'undefined'; => a = 10 + 'undefined' => a = '10undefined'
}
console.log(a); //输出 '10undefined'
// 题3:
var name ='lala';
name += 10; //name = 'lala' + 10 = 'lala10'
var type = typeof(name); //type = 'string'
if(type.length === 6){ //true
type.text = 'string'; //new String(type).text ='string'; 没地方赋值,deletel ;
}
console.log(type.text); //undefined