什么是object.keys

时间:2018-01-26 05:20:40

标签: javascript json node.js object properties

我记得object.keys返回对象的键。在我的代码中,我希望它返回包含questions对象数组中的问题的字符串。相反,它返回可能答案的数组。

object.keys是如何返回对象的属性的?

//var  answersCopy = questions[correctAnswerIndex]
[Object.keys(questions[correctAnswerIndex])[0]];

这是设置吗?我也开始玩它,就像在纸上我只是隔离所有东西然后再将这两个结合起来但我仍然不知道为什么object.keys得到了它的属性。

the Paper (Captains Log: 1#)

function populateRoundAnswers(questions, correctAnswerIndex, correctAnswerIndex2) {
  var ANSWER_COUNT = 4;


  var  GAME_LENGTH = 5;
     correctAnswerIndex= 0;
     correctAnswerIndex2= 2;

questions = [
{
    "Reindeer have very thick coats, how many hairs per square inch do they have?": [
        "13,000",
        "1,200",
        "5,000",
        "700",
        "1,000",
        "120,000"
    ]
},
{
    "The 1964 classic Rudolph The Red Nosed Reindeer was filmed in:": [
        "Japan",
        "United States",
        "Finland",
        "Germany"
    ]
},
 {
    "Santa's reindeer are cared for by one of the Christmas elves, what is his name?": [
        "Wunorse Openslae",
        "Alabaster Snowball",
        "Bushy Evergreen",
        "Pepper Minstix"
    ]
},
{
    "If all of Santa's reindeer had antlers while pulling his Christmas sleigh, they would all be:": [
        "Girls",
        "Boys",
        "Girls and boys",
        "No way to tell"
    ]
},
{
    "What do Reindeer eat?": [
        "Lichen",
        "Grasses",
        "Leaves",
        "Berries"
    ]
}    
];
  var  answersCopy = questions[correctAnswerIndex][Object.keys(questions[correctAnswerIndex])[0]];
return answersCopy;
}

populateRoundAnswers();

1 个答案:

答案 0 :(得分:1)

Object.keys返回在对象中找到的可枚举属性的数组。

在您的情况下,这行代码:

  var  answersCopy = questions[correctAnswerIndex][Object.keys(questions[correctAnswerIndex])[0]];

正在访问问题的答案。

questions[correctAnswerIndex] - 这会返回第一个问题 [Object.keys(questions[correctAnswerIndex])[0]] - 这会返回Reindeer have very thick coats, how many hairs per square inch do they have?

现在回顾answersCopy var,您可以访问数组中的第一个元素,然后查看返回答案数组的特定属性。

如果要获取Object键的数组,您所要做的就是将对象传递给Object类的keys方法。

var myObj = { name: 'Mike', age: 20 }
console.log(Object.keys(myObj)) // ['name', 'age']