你可以擴展對象的這樣的原型:
// Returns one key (any) of the value if it exists, or undefined if not
Object.defineProperty(Object.prototype, "keyOf", {
value: function(value) {
for (var key in this) if (this[key] == value) return key;
return undefined;
}
});
使用這種方式,而不是常見的Object.prototype.keyOf = ...
將與jQuery的工作,如果你使用它。
然後你可以使用這樣的:
var myArray = {...};
var index = myArray.keyOf(value);
它也將與正常工作數組:[...]
,所以你可以用它來代替indexOf
了。
記得使用三字符運營商,以檢查它是否未定義:
index === undefined // to check the value/index exists
index !== undefined // to check the value/index does not exist
當然,如果你願意,你可以改變函數的名稱,切記不要聲明一個名爲「未定義」的任何變量。
也請記住,爲的indexOf,它將返回定義最多一個關鍵,但它可能是一個以上的可能,所以在這種情況下,你需要像這樣(.keysOf(...)
):
// Returns all the keys of the value if it exists (an empty array if not)
Object.defineProperty(Object.prototype, "keysOf", {
value: function(value) {
var allKeys = [];
for (var key in this) if (this[key] == value) allKeys.push(key);
return allKeys;
}
});
你想第一個含有_exactly_ 280卡路里或至少280卡路里的熱量? – nnnnnn 2012-01-29 11:48:40
@nnnnnn - 一個簡單的反向查找 – 2012-01-29 11:49:56
很酷。遺憾的是,沒有內建的等同於'.indexOf()',但顯然它很簡單,可以創建一個簡短的函數來完成它。一個'for..in'循環是我目前的建議,只是因爲它受到舊版瀏覽器的支持。 – nnnnnn 2012-01-29 11:57:19