无法在 'Window' 上执行 'postMessage':需要 2 个参数,但只有 1 个存在

Failed to execute 'postMessage' on 'Window': 2 arguments required, but only 1 present

我目前有一个网络工作者试图接受 1 个参数

wworker = postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);
wworker.addEventListener('message', findDistance);

但是,控制台上不断弹出错误:"Uncaught TypeError: Failed to execute 'postMessage' on 'Window': 2 arguments required, but only 1 present."据我所知,postMessage 第二个参数是可选的。

这是我的 worker.js

var distance;

function findDistance(event) {
var destinationLat, destinationLon, originLat, originLon, haversineLat, haversineLon, thetaLat, thetaLon;
destinationLat = event.data[0] * (Math.PI/180);
destinationLon = event.data[1] * (Math.PI/180);
originLat = event.data[2] * (Math.PI/180);
originLon = event.data[3] * (Math.PI/180);
thetaLat = destinationLat - originLat;
thetaLon = destinationLon - originLon;
haversineLat = (1-Math.cos(thetaLat))/2;
haversineLon = (1-Math.cos(thetaLon))/2;
distance = 2 * 6376 * Math.asin(Math.sqrt(haversineLat + Math.cos(originLat) * Math.cos(destinationLat) * haversineLon));
postMessage(distance);
}

self.addEventListener('message', findDistance);

您没有在 Worker 上呼叫 .postMessage();您还在 for 循环的每次迭代中附加一个新的 message 事件。将 wworker.addEventListener('message', findDistance); 移出 for 循环,在 for 循环

内调用 wworker.postMessage()
var wworker = new Worker("assets/scripts/webworker.js");
wworker.addEventListener('message', findDistance);

for(i=0;i<lines.length;i++){
    var temp = lines[i].split(",");     

    wworker.postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);

    textCoords.shift();
    textCoords.shift();
}