使用.pop()值生成新数组

时间:2015-07-15 04:50:08

标签: javascript arrays canvas

我在画布上使用javascript绘制点,如下所示:

function addPointToMap(point) {
    var pointRadius = (document.getElementById(point.canvasId).height * (2 / 66)) / 2;
    var context = document.getElementById(point.canvasId).getContext("2d");
    context.beginPath();
    context.arc(point.x, point.y, pointRadius, 0, 2 * Math.PI);
    context.fillStyle = "red";
    context.fill();
}

我正在绘制的所有point都存储在数组pointMap中。我希望用户只有勾选一个复选框才能绘制一个点,如果没有勾选则绘制很多点。新点应该覆盖旧点。为了做到这一点,我决定将新点添加到数组中,然后删除旧点并刷新画布。问题是pointMap = pointMap.pop();返回一个空数组。如何获取阵列中的最新条目并删除所有其他条目?以下是我到目前为止的情况:

if (questionId == 41) {
    if (pointMap.length == 1) {
        //do nothing, user only has 1 point
    } else {
            console.log("PointMap: " + pointMap); //ex. returns [Point, Point] (Point is a custom class I wrote to store the point x and y values)
            pointMap = pointMap.pop(); //this line does not work
            console.log("PointMap: " + pointMap); //ex. returns []
            refreshCanvas();
        }
    }

我哪里错了?任何人都可以引导我朝着正确的方向前进吗?

1 个答案:

答案 0 :(得分:1)

pop会返回弹出的值,因此pointMap = pointMap.pop()会将您的数组引用替换为一个点。

如果您只想在复选框中选中一个点,只需覆盖它:

if (checkboxIsChecked) {
    // Only want one point, assign to index 0 (works whether the
    // array already has a point or not)
    pointMap[0] = theNewPoint;
} else {
    // Want to allow multiple points, push the point onto the array
    pointMap.push(theNewPoint);
}

如果用户可以在pointMap中有值的情况下选中该复选框,则您需要在检查时删除除最后一个之外的所有内容。在复选框的事件处理程序中:

if (checkboxIsChecked && pointMap.length > 1) {
    // Remove all entries except the last pushed one
    pointMap.splice(0, pointMap.length - 1);
}