JavaScript數組some()方法測試數組中的某個元素是否通過由提供的功能來實現測試。
語法
array.some(callback[, thisObject]);
下麵是參數的詳細資訊:
-
callback : 函數用來測試每個元素。
-
thisObject : 對象作為該執行回調時使用。
返回值:
如果某些元素通過測試則返回true,否則為false。
相容性:
這個方法是一個JavaScript擴展到ECMA-262標準; 因此它可能不存在在標準的其他實現。為了使它工作,你需要添加下麵的腳本代碼放到頂部:
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
例子:
<html>
<head>
<title>JavaScript Array some Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
document.write("Returned value is : " + retval );
var retval = [12, 5, 8, 1, 4].some(isBigEnough);
document.write("<br />Returned value is : " + retval );
</script>
</body>
</html>
這將產生以下結果:
Returned value is : false Returned value is : true
