使用 reduce 对 p5.Vector 个对象的数组求和

Using reduce to sum array of p5.Vector objects

以下代码在 reduce 行中抛出错误:

let vectors

function setup() {
    createCanvas(400,400);
    vectors = [];
    vectors.push(createVector(100,100));
    vectors.push(createVector(100,0));
    vectors.push(createVector(0,100));
    let s = vectors.reduce(p5.Vector.add, createVector(0,0));//error!
    console.log(s.x,s.y);
}

function draw() {
    vectors.forEach(v => line(0,0,v.x,v.y));
}

错误似乎出现在矢量 add 方法的 p5.js 代码中。错误消息开始:

p5.js says: There's an error as "set" could not be called as a function (on line 91666 in p5.js [https://cdn.jsdelivr.net/npm/p5@vv1.4.0/lib/p5.js:91666:22]).

这个错误最令人困惑的是,如果有问题的行被替换为:

,代码可以正常工作
let s = vectors.reduce((u,v) => p5.Vector.add(u,v), createVector(0,0));

这对我的预期应用来说已经足够了,但我想了解错误,而不是仅仅找到一种笨拙的方法来回避它。因此,我的问题是——为什么直接使用 reduce 和 p5.Vector.add 的尝试失败了,但将其包装在匿名函数中却成功了?

看起来 p5.Vector.Add 可以接受第三个可选参数:

p5.Vector.add(v1, v2, [target])

在那个例子中,它定义了目标:

p5.Vector: the vector to receive the result (Optional)

在您的原始版本中,您将参数从 reduce 函数传递到 p5.Vector.Add。但是,reduce 的第三个参数是 currentIndex,一个整数。