欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解JavaScript中的every()方法

 更新時間:2015年06月08日 12:04:04   投稿:goldensun  
這篇文章主要介紹了JavaScript中的every()方法,是JS入門學習中的基礎(chǔ)知識,需要的朋友可以參考下

 JavaScript 數(shù)組中的每個方法測試數(shù)組中的所有元素是否經(jīng)過所提供的函數(shù)來實現(xiàn)測試。
語法

array.every(callback[, thisObject]);

下面是參數(shù)的詳細信息:

  •     callback : 函數(shù)用來測試每個元素
  •     thisObject : 對象作為該執(zhí)行回調(diào)時使用

返回值:

返回true,如果此數(shù)組中的每個元素滿足所提供的測試函數(shù)。
兼容性:

這種方法是一個JavaScript擴展到ECMA-262標準;因此它可能不存在在標準的其他實現(xiàn)。為了使它工作,你需要添加下面的腳本的代碼在頂部:

if (!Array.prototype.every)
{
 Array.prototype.every = 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 false;
  }

  return true;
 };
}

例子:

<html>
<head>
<title>JavaScript Array every Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.every)
{
 Array.prototype.every = 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 false;
  }

  return true;
 };
}
function isBigEnough(element, index, array) {
 return (element >= 10);
}

var passed = [12, 5, 8, 130, 44].every(isBigEnough);
document.write("First Test Value : " + passed ); 
 
passed = [12, 54, 18, 130, 44].every(isBigEnough);
document.write("Second Test Value : " + passed ); 
</script>
</body>
</html>

這將產(chǎn)生以下結(jié)果:

First Test Value : falseSecond Test Value : true

相關(guān)文章

最新評論