ホームページ  >  記事  >  ウェブフロントエンド  >  JS の arrayreduce メソッドの詳細な分析 (コード付き)

JS の arrayreduce メソッドの詳細な分析 (コード付き)

奋力向前
奋力向前転載
2021-08-19 11:07:372492ブラウズ

前回の記事「 Vueのキー値がトランジション効果とアニメーション効果に及ぼす影響について簡単に解説(詳細コード解説) 」で、 Vue のキー値がトランジション効果とアニメーションに及ぼす影響を理解する。 JSのarrayreduceメソッドについては以下の記事でわかりやすく解説していますので、参考になると思います。

JS の arrayreduce メソッドの詳細な分析 (コード付き)

意味

reduce() メソッドは、アキュムレータと配列内の各要素 (左から右の順) に対して機能します。 ) は、単一の値に減らす関数を適用します。

構文

arr.reduce(callback[, initialValue])

パラメータ

callback配列内の各値を実行する関数。次の 4 つのパラメータが含まれます。 アキュムレータアキュムレータはコールバックの戻り値を蓄積します。これは、コールバックが最後に呼び出されたときに返された蓄積値、または initialValue (以下に示すように) です。

currentValue

処理される配列内の要素。 currentIndexOptional

配列内で処理されている現在の要素のインデックス。 initialValue が指定されている場合、インデックス番号は 0 であり、それ以外の場合、インデックスは 1 です。配列オプション

呼び出しの配列reduceinitialValueoptional

は、 callback の値への最初の呼び出しとして使用されます。パラメータ。初期値が指定されていない場合は、配列の最初の要素が使用されます。初期値のない空の配列に対して reduce を呼び出すと、エラーが報告されます。 セクションへのリンク戻り値関数の累積処理の結果

配列の検索[1, 2,3, 4,5]

// 1 遍历求和
let count = 0;
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
  count += arr[i];
}
console.log(count);
// output 15

// 2 eval
let count = eval([1, 2, 3, 4, 5].join("+"));
console.log(count);
// output 15

// 3 reduce
let count = [1, 2, 3, 4, 5].reduce((a, b) => a + b);
console.log(count);
// output 15

のすべての値の合計2次元配列を1次元に変換します

var flattened = [
  [0, 1],
  [2, 3],
  [4, 5],
].reduce((acc, cur) => acc.concat(cur), []);

配列内の各値を計算します。要素の出現数を計算します。

var names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];

var countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  } else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { &#39;Alice&#39;: 2, &#39;Bob&#39;: 1, &#39;Tiff&#39;: 1, &#39;Bruce&#39;: 1 }

#スプレッド演算子と initialValue を使用して、オブジェクト配列に含まれる配列をバインドします。

// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [
  {
    name: "Anna",
    books: ["Bible", "Harry Potter"],
    age: 21,
  },
  {
    name: "Bob",
    books: ["War and peace", "Romeo and Juliet"],
    age: 26,
  },
  {
    name: "Alice",
    books: ["The Lord of the Rings", "The Shining"],
    age: 18,
  },
];

// allbooks - list which will contain all friends&#39; books +
// additional list contained in initialValue
var allbooks = friends.reduce(
  function (prev, curr) {
    return [...prev, ...curr.books];
  },
  ["Alphabet"]
);

// allbooks = [
//   &#39;Alphabet&#39;, &#39;Bible&#39;, &#39;Harry Potter&#39;, &#39;War and peace&#39;,
//   &#39;Romeo and Juliet&#39;, &#39;The Lord of the Rings&#39;,
//   &#39;The Shining&#39;
// ]

配列の重複排除

let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((init, current) => {
  if (init.length === 0 || init[init.length - 1] !== current) {
    init.push(current);
  }
  return init;
}, []);
console.log(result); //[1,2,3,4,5]

最大値と最小値を取得する配列

let data = [1, 4, 2, 2, 4, 5, 6, 7, 8, 8, 9, 10];
//取最小值
let min = data.reduce((x, y) => (x > y ? y : x));
//取最大值
let max = data.reduce((x, y) => (x > y ? x : y));

ES5 の実装

if (!Array.prototype.reduce) {
  Object.defineProperty(Array.prototype, "reduce", {
    value: function (callback /*, initialValue*/) {
      if (this === null) {
        throw new TypeError(
          "Array.prototype.reduce " + "called on null or undefined"
        );
      }
      if (typeof callback !== "function") {
        throw new TypeError(callback + " is not a function");
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;
      // >>表示是带符号的右移:按照二进制把数字右移指定数位,高位如符号位为正补零,符号位负补一,低位直接移除
      //  >>>表示无符号的右移:按照二进制把数字右移指定数位,高位直接补零,低位移除。

      // Steps 3, 4, 5, 6, 7
      var k = 0;
      var value;

      if (arguments.length >= 2) {
        value = arguments[1];
      } else {
        while (k < len && !(k in o)) {
          k++;
        }

        // 3. 长度为0 且初始值不存在 抛出异常
        if (k >= len) {
          throw new TypeError(
            "Reduce of empty array " + "with no initial value"
          );
        }
        value = o[k++];
      }

      // 8. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kPresent be ? HasProperty(O, Pk).
        // c. If kPresent is true, then
        //    i.  Let kValue be ? Get(O, Pk).
        //    ii. Let accumulator be ? Call(
        //          callbackfn, undefined,
        //          « accumulator, kValue, k, O »).
        if (k in o) {
          value = callback(value, o[k], k, o);
        }

        // d. Increase k by 1.
        k++;
      }

      // 9. Return accumulator.
      return value;
    },
  });
}

推奨学習:

JavaScript ビデオ チュートリアル

以上がJS の arrayreduce メソッドの詳細な分析 (コード付き)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はchuchur.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。