我是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>发布于 2018-10-06 18:08:26
当您在数组上调用forEach时,forEach中的代码将调用您传递给它的函数"for each“数组中的每个条目,并将条目传递给函数(以及其他一些东西)。所以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的thisArg和使用特定的this值调用callback。)
记录每个步骤的实时示例:
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;
}
第二,MDN是一个很好的JavaScript信息资源(以及Jaromanda X's recommendation和CSS)。
发布于 2018-10-06 18:11:44
rect变量表示数组event.data中的一项。
在数组(event.data)上调用.forEach()方法时,此方法将在内部迭代数组的每一项,并在每次迭代期间将当前数组项传递给您提供的回调函数,在本例中为该函数:
function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
}因此,rect是event.data当前迭代的当前项。希望这能有所帮助!
发布于 2018-10-06 18:17:03
‘'rect’是通过使用forEach迭代返回的项的名称。你可以随心所欲地叫它,只是碰巧有人叫它rect。
你可以叫它任何你想要的名字
arr.forEach(name ()=> console.log(name))
arr.forEach(yourDogsName ()=> yourDogsName.height)https://stackoverflow.com/questions/52677916
复制相似问题