【发布时间】:2010-01-15 03:02:02
【问题描述】:
还是只需要循环并检查每个元素?
【问题讨论】:
标签: javascript jquery arrays
还是只需要循环并检查每个元素?
【问题讨论】:
标签: javascript jquery arrays
Mozilla JS 实现和其他现代 JS 引擎都采用了Array.prototype.indexOf 方法。
[1].indexOf(1) // 0
如果不包含它,则返回 -1。
IE当然也可能其他浏览器没有,官方代码:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
【讨论】:
如果你使用 jQuery:jQuery.inArray( value, array )
更新:指向新 jQuery API 的 URL
【讨论】:
您可以查看 Javascript 1.6 的某些功能。
如果您只想知道它是否在其中,您可以使用indexOf,例如,这将满足您的需求。
更新:
如果您访问此页面,http://www.hunlock.com/blogs/Mastering_Javascript_Arrays,您可以找到在 IE 和任何其他没有您想要使用的内置功能的浏览器上使用的功能。
【讨论】:
这是拥有自己的indexOf 方法的一种方法。此版本利用环境中存在的Array.prototype.indexOf 方法;否则,它使用自己的实现。
(此代码已经过测试,但我不保证它在所有情况下的正确性。)
// If Array.prototype.indexOf exists, then indexOf will contain a closure that simply
// calls Array.prototype.indexOf. Otherwise, indexOf will contain a closure that
// *implements* the indexOf function.
//
// The net result of using two different closures is that we only have to
// test for the existence of Array.prototype.indexOf once, when the script
// is loaded, instead of every time indexOf is called.
var indexOf =
(Array.prototype.indexOf ?
(function(array, searchElement, fromIndex) {
return array.indexOf(searchElement, fromIndex);
})
:
(function(array, searchElement, fromIndex)
{
fromIndex = Math.max(fromIndex || 0, 0);
var i = -1, len = array.length;
while (++i < len) {
if (array[i] === searchElement) {
return i;
}
}
return -1;
})
);
【讨论】: