>  기사  >  웹 프론트엔드  >  JavaScript의 Reduce() 메소드 사용에 대한 자세한 설명

JavaScript의 Reduce() 메소드 사용에 대한 자세한 설명

高洛峰
高洛峰원래의
2016-12-28 09:44:471331검색

JavaScript 배열 Reduce() 메소드는 배열의 두 값(왼쪽에서 오른쪽으로)에 동시에 함수를 적용하여 하나의 값으로 줄이는 것입니다.
구문

array.reduce(callback[, initialValue]);

파라미터의 세부 내용은 다음과 같습니다.

콜백: 배열의 각 값에 대해 함수가 실행됩니다.

initialValue:

을 사용하여 콜백의 첫 번째 호출에 대한 첫 번째 인수인 개체 반환 값:

배열의 축소된 단일 값을 반환합니다.
호환성:

이 메소드는 ECMA-262 표준에 대한 JavaScript 확장이므로 다른 표준 구현에는 없을 수도 있습니다. 작동하게 하려면 코드 상단에 다음 스크립트를 추가해야 합니다.

if (!Array.prototype.reduce)
{
 Array.prototype.reduce = function(fun /*, initial*/)
 {
  var len = this.length;
  if (typeof fun != "function")
   throw new TypeError();
 
  // no value to return if no initial value and an empty array
  if (len == 0 && arguments.length == 1)
   throw new TypeError();
 
  var i = 0;
  if (arguments.length >= 2)
  {
   var rv = arguments[1];
  }
  else
  {
   do
   {
    if (i in this)
    {
     rv = this[i++];
     break;
    }
 
    // if array contains no values, no initial value to return
    if (++i >= len)
     throw new TypeError();
   }
   while (true);
  }
 
  for (; i < len; i++)
  {
   if (i in this)
    rv = fun.call(null, rv, this[i], i, this);
  }
 
  return rv;
 };
}

예:



JavaScript Array reduce Method




다음과 같은 결과가 나타납니다.

total is : 6
PHP 중국어 웹사이트를 팔로우하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.