js转换成布尔类型boolean

Posted 勾践

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js转换成布尔类型boolean相关的知识,希望对你有一定的参考价值。

/**
 * 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

 

以上是关于js转换成布尔类型boolean的主要内容,如果未能解决你的问题,请参考以下文章

转换成布尔

JS 类型转换

变量的数据类型转换

前端面试 JavaScript— JS中类型转换有哪几种?

js-20170612-数据类型转换

布尔类型是啥意思?