pe**********@gmail.com wrote:
Marc Miller wrote: Javascript is new to me. Is there any way to express
if (var IN (val1, val2, val3, val4)) without using
<nitpick>This can never work because `var' is a reserved word.</nitpick>
something like
if (var == val1 && var == val2 && var == val3)
or looping thru an array?
See the July 22, 2005 blog entry
http://trimpath.com/blog/
This might be what you want.
You could have posted a usable URL:
<URL:http://trimpath.com/blog/?m=200507>
or even the original one:
<URL:http://laurens.vd.oever.nl/weblog/items2005/setsinjavascript/>
However, this approach is not new (only its implementation could be),
and the solution introduces a dependency on the `in' operator, not
supported before JavaScript 1.4 (SSJS/Gecko), JScript 5.0 (IE 5.0),
ECMAScript Ed. 3, and, it is current form on Object literals, not
supported before JavaScript 1.3 (NN4), JScript 3.0 (IE 3.0), ECMAScript
Ed. 3 (that part can be either ignored, or fixed with `new Object').
It is one of the more elegant solutions, but it has a problem: because
with the `in' operator every first operand is converted to string (and
all property names are strings), one cannot distinguish between
differently typed values. For example,
2 in set("2", 3, 4)
yields true, although the "needle" is of type number, and the haystack
has only a value of type string.
Another solution that does not depend on those versions (and does not
have the type problem if strict equals is used if supported), would be
to define a function/method like the boolean operator:
function inArray(v, a)
{
for (var i = 0, len = a.length; i++)
{
if (v == a[i]) return true;
}
return false;
}
if (inArray(v, new Array(val1, val2, val3, val4))
{
// ...
}
I have implemented something similar in JSX:array.js. However, the Array
object is not needed, it is just there for distinguishing "needle"
(primitive value) and "haystack" (refers to the Array object encapsulating
the array data structure):
function inSet(v)
{
for (var i = 1, len = arguments.length; i++)
{
if (v == arguments[i]) return true;
}
return false;
}
if (inSet(v, val1, val2, val3, val4))
{
// ...
}
JavaScript 1.6 (Firefox 1.5+) also provides for a built-in solution[1] with
arrays and a closure:
function inArray(needle, aHaystack)
{
return aHaystack.some(
function(v, i, a)
{
return v === needle;
});
}
if (inArray(v, [val1, val2, val3, val4]))
{
// ...
}
With Array.prototype.forEach() and equivalents one could even count the
occurrences of v in the set/array. Since (±)0 evaluates to `false' and
any other number value except NaN to `true', that would be a worthwhile
extension, perhaps better be triggered by an additional optional argument
that defaults to `false'.
PointedEars
___________
[1] <URL:http://developer.mozilla.org/en/docs/New_in_JavaScript_1.6>