var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;在JS中有没有更简单的方法来做到这一点?
发布于 2010-09-28 10:02:27
你可以只使用对象。
var obj = {foo: true, baz: false, xyz: true};
obj.baz = true;发布于 2010-09-28 11:13:42
在您的示例中,您实际上只需要将"bar“替换为true;生成的数组将类似于[foo, true, xyz]。
我认为假设您所要求的是一种替代方案,而不是使用一组用于键的数组和一组用于值的数组,这是最好的方法。
但是,您可以使用关联数组或对象来维护键值对。
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如果你使用这种方法,重要的是要意识到一些事情:
array.length不再适用,因为它只按数字索引计算数组,它不计算数组属性,这就是关联数组中的键是什么。由于[foo, bar, xyz, bar, foobar, foo],其中索引应返回除IE<=8以外的任何浏览器中的第一个匹配项
做你特别要求的事情的另一种方法是:
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 ]https://stackoverflow.com/questions/3809141
复制相似问题