This question already has answers here:
What's the difference between using “let” and “var”?
                                
                                    (33个答案)
                                
                        
                        
                            Do let statements create properties on the global object?
                                
                                    (5个答案)
                                
                        
                                在10个月前关闭。
            
                    
如何动态获得类似于PHP中constant()的常量值?

在下面,我想访问HELL_NO,但是在变量中有NO。为什么返回undefined



const HELL_YES='warm';
const HELL_NO='cool';
var pick='NO';
console.log(window['HELL_'+pick]);

最佳答案

您可以使用eval



const HELL_YES='warm';
const HELL_NO='cool';
var pick='NO';
console.log(eval("HELL_" + pick));





编辑

因为evalevil,所以应该改用一个对象:



const obj = {
  HELL_YES: "warm",
  HELL_NO: "cool"
};

console.log(obj["HELL_" + "YES"]);

10-04 17:17