简体   繁体   English

访问对象属性时如何避免eval?

[英]How to avoid eval when accessing object properties?

I've read quite a lot but I can't figure out the following:我已经阅读了很多,但我无法弄清楚以下几点:

var eventCity = [
    {date: 'Apr 11 2017', type: 'alpha'},
    {date: 'Apr 26 2017', type: 'beta'}
];

var currentCity = 'eventCity';  // this is generated dynamically

var aDate = eval(currentCity)[0].date;

How to avoid the use of eval() maintaining the same result ( aDate = 'Apr 11 2017' ) ?如何避免使用eval()保持相同的结果( aDate = 'Apr 11 2017' )?

Why not use an object and take the dynamic value as key?为什么不使用对象并以动态值作为键?

var object = {
        eventCity: [
            { date: 'Apr 11 2017', type: 'alpha' },
            { date: 'Apr 26 2017', type: 'beta' }
        ]
    },
    currentCity = 'eventCity',  // this is generated dynamically
    aDate = object[currentCity][0].date;

var options = [] var 选项 = []

options['eventCity']=[ {date: 'Apr 11 2017', type: 'alpha'}, {date: 'Apr 26 2017', type: 'beta'} ]; options['eventCity']=[ {date: 'Apr 11 2017', type: 'alpha'}, {date: 'Apr 26 2017', type: 'beta'} ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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