Home > Back-end >  JS Object Mapping Quesions
JS Object Mapping Quesions

Time:09-23

I've been trying to understanding this part of the code:

if(stack.length > 0 && map[stack[stack.length - 1]] === s[i])

at line 9. What does the "map[stack[stack.length-1]]" mean? At first I thought the map is an object, but I think you are supposed to add " " mark around the properties. Is map a data structure? if it is, How can I use this data structure?

    var stack = [];
    var len =  s.length;
    var map = {
        '(': ')',
        '[': ']',
        '{': '}',
    };
    for(var i = 0; i<len; i  ){
        if(stack.length > 0 && map[stack[stack.length - 1]] === s[i]) {
            stack.pop();
        }else{
            stack.push(s[i]);
        }

    }
    return stack.length === 0;
};

CodePudding user response:

Map is an object and

map[stack[stack.length - 1]]

is the property of 'map' wich key is the value of the last element of the array stack. As properties of an object can be accessed both these ways

const object = {
"property1" : value1,
"property2" : value2,
}
object.property1 == object['property1']; // is true
object.property2 == object['property2']; // is also true
  • Related