This question already has answers here:
Dynamically access object property using variable
                                
                                    (15个答案)
                                
                        
                去年关闭。
            
        

我有一个这样的对象SentimentScore

SentimentScore:
{Mixed: 0.00005830301233800128,
Negative: 0.0011920471442863345,
Neutral: 0.9854754209518433,
Positive: 0.013274261727929115}


我想要基于我在变量中设置的值,例如:

var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';


我想改用变量,以查找SentimentScore的字段值。

像SentimentScore.finalSentiment1这样的值应为0.0011920471442863345。

是否可以不使用条件语句?如果是,怎么办?提前致谢。

最佳答案

您可以使用计算的([])属性,该属性使您可以动态地将表达式作为属性名称计算为对象:



var SentimentScore = {
  Mixed: 0.00005830301233800128,
  Negative: 0.0011920471442863345,
  Neutral: 0.9854754209518433,
  Positive: 0.013274261727929115
}

var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';

console.log(SentimentScore[finalSentiment1]);
console.log(SentimentScore[finalSentiment2]);

07-26 08:06