Home > Net >  I'm trying to stop a constant dictionary from being modified in a function
I'm trying to stop a constant dictionary from being modified in a function

Time:06-06

I'm writing a JavaScript University building indoor map program, and the displaying route code works, however my dictionary which stores the graph is being changed within the function and I don't have much experience in JavaScript and can't spot the problem.

this is the Dictionary;

const TheGraph = {
    "A" : { 
        "Coordinates" : [3776, 625],
        "Links" : {"C": 1}
    },
    "B" : { 
        "Coordinates" : [970, 910],
        "Links" : {"C" : 5, "G" : 5}
    },
    ....

}

And this is where i believe is the problem

button.addEventListener('click', () =>{
        var possRoutes = []; // stores the points
        const lineString = new H.geo.LineString();
        var heading = (document.getElementById('room-header')).innerHTML 
        var heading = heading.substring(5); // gets the name of the room
        for (const x of (Rooms[heading][1])){
            possRoutes.push(findShortestPath(TheGraph, "A", x))
        } // finds the shorted path
        possRoutes.reduce(function(prev, curr) {
            return prev.distance < curr.distance ? prev : curr;
        });
        for (var cor in possRoutes[0].path){
            var point = TheGraph[point = possRoutes[0].path[cor]].Coordinates // gets the coordinate from the dictionary
            var distanceToOrigin = pythagorean(point[1], point[0])//maths
            var ang = 1.5708-(angle   Math.atan(point[0]/point[1]))
            point[0] = originX-(Math.cos(ang)*distanceToOrigin)*scaleX
            point[1] = originY-(Math.sin(ang)*distanceToOrigin)*scaleY
            lineString.pushPoint({lat: point[0], lng: point[1]}) // adds the point to the map
        }
        point = Rooms[heading][0]
        var distanceToOrigin = pythagorean(point[1], point[0])
        var ang = 1.5708-(angle   Math.atan(point[0]/point[1]))
        point[0] = originX-(Math.cos(ang)*distanceToOrigin)*scaleX
        point[1] = originY-(Math.sin(ang)*distanceToOrigin)*scaleY
        lineString.pushPoint({lat: point[0], lng: point[1]})
        console.log(TheGraph)
        path = new H.map.Polyline(
            lineString, { style: { lineWidth: 4,
                strokeColor: '#2600ff' }}
        )
        F0.addObject(path);//displays the route on the map
    })

CodePudding user response:

const means that the name theGraph cannot be reassigned to refer to something else, not that the thing it refers to is immutable. You’re changing the elements in the coordinates array in the lines that start with point[0] etc.

CodePudding user response:

This fixed my problem.

var point = Object.assign({}, point);

https://stackoverflow.com/a/29050089/18367450

  • Related