var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
Is there an easier way to do this in JS?
var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
Is there an easier way to do this in JS?
All values in that array are already undefined. (You edited your post) I don't know why you are complaining about 2 whole lines of code though.
Short answer no, you can't access an index of an array without knowing the index.
One IE safe way would be to create a prototyped function which lets you set it easily:
Array.prototype.setKeysWithValue = function(keyValue,newValue)
{
var i;
for (i in this)
{
if (this[i] === keyValue)
this[i] = newValue;
}
}
This can then be used like:
var arr = ['foo','bar','xyz'];
arr.setKeysWithValue('bar',true);
You could just use objects.
var obj = {foo: true, baz: false, xyz: true};
obj.baz = true;
In your example you would really only be replacing "bar" with true; your resultant array would look like [foo, true, xyz]
.
I think it's assumed that what you're asking for is an alternative to having one set of arrays for keys and one set of arrays for values, of which there is no better way.
However, you can use an associative array, or objects, to maintain a key value pair.
var f = false, t = true;
// associative array
var arr = new Array();
arr["foo"] = arr["bar"] = arr["foobar"] = f;
arr["bar"] = t;
// object
var obj;
obj = {"foo":f, "bar":f, "foobar":f};
obj["bar"] = t;
// the difference is seen when you set arr[0]=t and obj[0]=t
// the array still maintains it's array class, while the object
// is still a true object
It's important to realize a few things if you use this method:
array.length
no longer applies, as it only accounts arrays by numerical index, it does not count array properties, which is what the keys in an associative array are[foo, bar, xyz, bar, foobar, foo]
, where the index should return the first occurrence in anything browser other than IE<=8One other way to do what you were specifically asking is:
Array.prototype.replace = function(from,to){ this[this.indexOf(from)]=to; };
Array.prototype.replaceAll = function(from,to){ while(this.indexOf(from)>=0){this[this.indexOf(from)]=to;} };
var arr = new Array();
arr=[ "foo", "bar", "foobar", "foo" ];
arr.replace("bar",true); // [ "foo", true, "foobar", "foo" ]
arr.replaceAll("foo",false); // [ false, true, "foobar", false ]