javascript - 访问对象内部键的值

标签 javascript function constructor key

我知道有一些与此极其相似的问题,但我似乎无法解决任何问题。

为了简洁起见,我将对此进行总结。我有这个构造函数,其中将字符串指定为键的值(赋值)。

var Quote = function() {
  this.quote1 = 'You can discover more about a person in an hour of play than in a year of conversation.';
  this.quote2 = 'Nothing is at last sacred but the integrity of your own mind.';
  this.quote3 = 'We have to fight them daily, like fleas, those many small worries about the morrow, for they sap our energies.';
  this.quote4 = 'Ethics are so annoying. I avoid them on principle.';
  this.quote5 = "Never trust anything that can think for itself if you can't see where it keeps its brain.";
};

module.exports = Quote;

使用 AJAX,我将构造函数内的键值打印到静态页面。但是...我只成功打印了“quote1”、“quote2”等...(只是键的名称)。

这就是我访问构造函数的函数的样子。我的问题是:如何访问分配给构造函数内键的字符串值?这可能吗?

提前谢谢您。

module.exports = function(object) {
  var propArray = Object.keys(object);
  var randomProp = propArray[Math.floor(Math.random() * propArray.length)];
  return {quote: randomProp};
};

最佳答案

在您的函数内,您应该能够使用以下键访问报价:

object[randomProp]

在 JavaScript 中,可以使用方括号表示法访问对象属性。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects .

关于javascript - 访问对象内部键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161295/

相关文章:

javascript - Webpack 4 基本 React js hello world 失败并显示 "Module parse failed: Unexpected token"

php - mysql函数,当输入客户号码时返回带有字符串的所有地址

jquery - 使用 jquery contains 内部函数?

scala - 覆盖成员和惰性 val

Scala构造函数重载参数不生效

javascript - 有没有一种方法可以用动态名称处理 javascript 函数?

javascript - 理解 RegisterStartupScript : How often will the JavaScript code be called?

javascript - 无法忽略nuxtjs中的文件夹

function - 对常量值使用def vs. val有什么含义

c++ - 继承带有默认参数的构造函数?