/** * js转换成布尔值 * a.转换方法:Boolean(var) * b.数字转换成布尔,除了0与NaN,其余都是true * c.字符串转换成布尔,除了空串"",其余都是true * d.null与undefined会转换成false * e.对象会转换成true */ // 数字 var foo = 1888; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: number, Boolean(foo): true // 0 var foo = 0; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: number, Boolean(foo): false // NaN var foo = NaN; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: number, Boolean(foo): false // 字符串 var foo = 'hello'; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: string, Boolean(foo): true // '' var foo = ''; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: string, Boolean(foo): false // null var foo = null; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: object, Boolean(foo): false // undefined var foo = undefined; console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: undefined, Boolean(foo): false // 对象 // var foo = object; // console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // Uncaught ReferenceError: object is not defined // Object() var foo = Object(); console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: object, Boolean(foo): true // new Object() var foo = new Object(); console.log(`typeof foo: ${typeof foo}, Boolean(foo): ${Boolean(foo)}`); // typeof foo: object, Boolean(foo): true // 声明未赋值变量 var bar; console.log(`typeof bar: ${typeof bar}, Boolean(bar): ${Boolean(bar)}`); // typeof bar: undefined, Boolean(bar): false // 函数名f function f() { // } console.log(`typeof f: ${typeof f}, Boolean(f): ${Boolean(f)}`); // typeof f: function, Boolean(f): true // 函数f() function f() { // } console.log(`typeof f(): ${typeof f()}, Boolean(f()): ${Boolean(f())}`); // typeof f(): undefined, Boolean(f()): false // 函数f(a, b) // function f(a, b) { // // // } // console.log(`typeof f(a, b): ${typeof f(a, b)}, Boolean(f(a, b)): ${Boolean(f(a, b))}`); // Uncaught ReferenceError: a is not defined // 函数f(a = 0, b = '') function f(a = 0, b = '') { // } console.log(`typeof f(a = 0, b = ''): ${typeof f(a = 0, b = '')}, Boolean(f(a = 0, b = '')): ${Boolean(f(a = 0, b = ''))}`); // typeof f(a = 0, b = ''): undefined, Boolean(f(a = 0, b = '')): false // 带返回值函数fooBar(a = 10) function fooBar(a = 10) { return a; } console.log(`typeof fooBar(a = 10): ${typeof fooBar(a = 10)}, Boolean(fooBar(a = 10)): ${Boolean(fooBar(a = 10))}`); // typeof fooBar(a = 10): number, Boolean(fooBar(a = 10)): true