简体   繁体   中英

Javascript: Pass Hash Key as Parameter

I have a hash called 'tag' with several keys, including width, height, x, and y. I also have this function:

function invertCoordinates(measure, coordinate){
    tag.measure = tag.measure * -1;
    tag.coordinate = tag.coordinate - tag.measure;
}

In which I want to pass tag's keys:

invertCoordinates(width, x);

or

invertCoordinates(height, y);

Unfortunately, I can't pass keys in this manner. Is there some other way to accomplish this?

使用数组访问符号( tag[measure] )并将键作为字符串传递: invertCoordinates('width', 'x')

Can you do:

function invertCoordinates(measure, coordinate){
    tag[measure] = tag[measure] * -1;
    tag[coordinate] = tag[coordinate] - tag[measure];
}

where measure and coordinate are strings? For instance:

invertCoordinates("width", "x");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM