javascript - 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>
解决方案
当您调用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
调用。)callback
this
记录每个步骤的实时示例:
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)的好资源。
推荐阅读
- excel - 在数据透视表中为多个时间列分组时间
- angular - Ionin 3 - NavParams 出现未定义的错误
- authentication - 我应该只在应用程序或 Apache 上设置 Keycloak
- android - TextView大小问题android
- elasticsearch - 使用 Logstash 从 ES 中删除索引
- c# - 依赖注入导致不必要的实现
- python-3.x - Tensorflow 中的一些张量操作
- c# - 定时器在全局文件中的 iis 服务器上无法正常工作
- sql - SQL:ORDER BY 语句中的嵌套大小写
- bash - Travis 构建的意外标记“else”附近的语法错误