首页 > 解决方案 > JavaScript 函数参数 - 初学者问题

问题描述

我是 JavaScript 新手,来自 Python。我很难理解“rect”的来源以及它是如何在以下脚本中传递的(我从 tracking.js 中获取的):任何帮助将不胜感激,我相信这个问题也可能会有所帮助任何其他来自 Python 的。

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>tracking.js - first tracking</title>
  <script src="../build/tracking-min.js"></script>
</head>
<body>
  <video id="myVideo" width="400" height="300" preload autoplay loop muted></video>
  <script>
  var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);

  colors.on('track', function(event) {
    if (event.data.length === 0) {
      // No colors were detected in this frame.
    } else {
      event.data.forEach(function(rect) {
        console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
      });
    }
  });

  tracking.track('#myVideo', colors);
  </script>
</body>
</html>

标签: javascriptdom-events

解决方案


当您调用forEach一个数组时,其中的代码forEach调用您将“为每个”数组中的条目传递给它的函数,将条目传递给函数(以及其他一些东西)。rect数组中的每个条目也是如此,按顺序排列。

在内部,省略了一些细节,forEach看起来像这样:

function forEach(callback) {
    // Here, `this` is the array `forEach` was called on
    for (let index = 0, len = this.length; index < len; ++index) {
        callback(this[index], index, this);
//               ^^^^^^^^^^^--- this is received by your callback as `rect`
    }
}

(为清楚起见,我省略的主要细节之一是forEach's和使用特定值thisArg调用。)callbackthis

记录每个步骤的实时示例:

function pseudoForEach(callback) {
    console.log("Start of pseudoForEach");
    for (let index = 0, len = this.length; index < len; ++index) {
        console.log(
            "Calling callback with: this[index] = " + this[index] +
            ", index = " + index + ", and this = (the array)"
        );
        callback(this[index], index, this);
    }
    console.log("End of pseudoForEach");
}

Object.defineProperty(Array.prototype, "pseudoForEach", {
    value: pseudoForEach,
    configurable: true,
    writable: true
});

var a = ["one", "two", "three"];
console.log("About to call pseudoForEach");
a.pseudoForEach(function(rect) {
    console.log("In callback, rect = " + rect);
});
console.log("Done with pseudoForEach call");
.as-console-wrapper {
  max-height: 100% !important;
}


赞同 Jaromanda X 的建议MDN是 JavaScript 信息(以及 HTML 和 CSS)的好资源。


推荐阅读