var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
在JS中有更簡單的方法嗎?JavaScript數組 - 替代arr [arr.indexOf()]?
var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
在JS中有更簡單的方法嗎?JavaScript數組 - 替代arr [arr.indexOf()]?
你可以只使用對象。
var obj = {foo: true, baz: false, xyz: true};
obj.baz = true;
你不是指'obj.baz = true'嗎? – 2010-09-28 02:07:29
我是,兒子! – Louis 2010-09-28 02:11:36
您還應該注意'obj [「baz」]'語法,這是我認爲OP需要的。 – 2010-09-28 02:23:54
該數組中的所有值都是未定義的。
(你編輯了你的帖子)我不知道你爲什麼抱怨2整行代碼。
簡短回答否,不能在不知道索引的情況下訪問數組的索引。
一個IE安全的方式是創建一個原型功能,可讓您輕鬆設置:
Array.prototype.setKeysWithValue = function(keyValue,newValue)
{
var i;
for (i in this)
{
if (this[i] === keyValue)
this[i] = newValue;
}
}
這可以被使用,如:
var arr = ['foo','bar','xyz'];
arr.setKeysWithValue('bar',true);
在你的例子中,你真的只能用true替換「bar」您的結果數組看起來像[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 ]
下面是'.indexOf()'的一些替代方法,它具有平淡的IE支持,http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array/143863#143863 – Robert 2010-09-28 02:00:41
歡迎來到堆棧溢出,不要忘記選擇最合適的答案,並提出你認爲有用的答案。 – vol7ron 2010-09-28 03:22:45