Prev: Ajax problem
Next: java & tomcat server
From: aoshi on 25 Mar 2010 08:32 Hi Does anyone know why the following statement return true: ![] == false thanks aoshi
From: Richard Cornford on 25 Mar 2010 08:44 On Mar 25, 12:32 pm, aoshi wrote: > Does anyone know why the following statement return > true: ![] == false It is more accurate to say that it evaluates to true, as it is an expression and returning values is something that functions do. The pair of square brackets (- [] -) result in the creation of an empty Array object. The NOT operator (- ! -) type converts its operand (the empty Array object) into a boolean value using the language's type conversion rules, where all objects (including Array objects) type-converted to boolean become boolean true, and then it inverts that boolean value to become the result of the NOT operation. Thus ! applied to any object results in a boolean false value. Boolean false is equal to boolean false so the result of the whole expression is boolean true. Richard.
From: Dmitry A. Soshnikov on 25 Mar 2010 09:11 On Mar 25, 3:32 pm, aoshi <imran_mu...(a)yahoo.com> wrote: > Hi > > Does anyone know why the following statement return true: ![] == > false > > thanks > Because type conversion rules. I guess you just want to test whether array is empty. If so (and if correct array indexes are meant) then you can use .length property test, which should be 0 in this case. var a = []; if (!a.length) { ... } If other properties should be considerate also, you can use some general test function which use for..in loops with checking all own enumerable properties: function isEmpty(object) { for (var k in object) // if (object.hasOwnProperty(k)) return true; return false; } var a = []; a['notArrayIndex'] = 10; a.length; // 0 if (isEmtry(a)) { // false .. } P.S.: if you program only for some concrete implementations (e.g. Gecko), for the last case you can use non-standard extensions such as __count__ (if you won't override it with your own such property): a.length; // 0 a.__count__; 1 Dmitry.
|
Pages: 1 Prev: Ajax problem Next: java & tomcat server |