function bouncer(arr) { // Don't show a false ID to this bouncer. function a(b) { if(b !== false) { return b; } } arr = arr.filter(a); return arr; } bouncer([7, 'ate', '', false, 9]);
I need to return only true Boolean operators, and when I run this code, it works. However, I'm rather confused because my if statement will work, be it b! == true or b! == false. Can someone explain the reason why this works in both directions?
I solved a similar problem and came up with this:
function bouncer(arr) { return arr.filter(Boolean); } bouncer([7, 'ate', '', false, 9]); // returns ['7','ate','9']
The easiest way to do this is:
function bouncer(arr) { return arr.filter(x => !!x); }
, . true false :
function bouncer(arr) { arr = arr.filter(function(x) { console.log(x === true) if(x !== false) { return true; } }); return arr; }
:
function bouncer(arr) { return arr.filter(function(x) { console.log(x === true) return x !== false; }); }
.filter() ES5.
, . , !
, :
arr.filter(Boolean)
arr.filter( function(x) { return Boolean(x); });
Boolean() , true, true, false, false!
var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5]; var b = a.filter(Boolean); // [1, 2, "b", {}, 3, 5];
: .
, JavaScript "" "". (, ..)
, , :
function bouncer(arr) { // Don't show a false ID to this bouncer. function a(b) { if(typeof(b) === 'boolean' && !b) { return new Boolean(b); } } arr = arr.filter(a); return arr; } bouncer([7, 'ate', '', false, 9, true]);