I have such an array:
arr['key1'] = true;
arr['key2'] = true;
arr['key3'] = true;
...
arr['keyN'] = true;
How to determine, have anyone key a "false" value?
I have such an array:
arr['key1'] = true;
arr['key2'] = true;
arr['key3'] = true;
...
arr['keyN'] = true;
How to determine, have anyone key a "false" value?
are you new to Javascript?
for(var i = 0; i < arr.length; i++) {
if(arr[i] === false) {
// do something
}
}
Unfortunately, the only way to do this until recently was to loop through the array; if you're using this in a browser-based app, you'll probably have to do it that way. There are new array features in ECMAScript 5th edition (the new JavaScript) that let you do this in a slightly different way, but only some browsers support them (and I'm not sure they'd necessarily be applicable).
But what you've described in your question is more a map (or "dictionary;" sometimes called an associative array) than an array (numerically-based indexed thingy). In JavaScript, "array" is usually used to mean numerically-indexed arrays (e.g., created via []
or new Array
), and "object" is usually used for maps (because all JavaScript objects are maps). (This can be a bit confusing, because arrays are objects. But don't worry about that.) So this is an array:
var a = ['one', 'two', 'three'];
...whereas this is an object ("map", "dictionary", "associative array"):
var o = {key1: 'one', key2: 'two', key3: 'three'};
Your use of non-numeric indexes suggests you're really using a map, not an array. The search loop looks something like this on maps:
var key, found;
found = false;
for (key in arr) {
if (arr.hasOwnProperty(key)) {
if (!arr[key]) { // <== There are alternatives, see notes below
found = true;
break;
}
}
}
There I've used if (!arr[key])
to check for the false
value. That will actually stop on false
, undefined
, null
, or an empty string. If you really, really want false
, use if (arr[key] === false)
instead.
function hasFalse(arr) {
for (i in arr) {
if (!arr[i]) {
return true;
}
}
return false;
}
This returns as soon as a single false is found.