【问题标题】:converting two-dimensional array into array object in JavaScript在 JavaScript 中将二维数组转换为数组对象
【发布时间】:2015-06-22 07:25:38
【问题描述】:

我有以下二维数组代码

var questions = [
  ['How many states are in the United States?', 50],
  ['How many continents are there?', 7],
  ['How many legs does an insect have?', 6]
];

并将其转换为数组对象

var questions = [
 { question: 'How many states are in the United States?', answer: 50 },
 { question: 'How many continents are there?', answer: 7 },
 { question: 'How many legs does an insect have?', answer: 6 }
]; 

并有相应的for循环。

for (var i = 0; i < questions.length; i += 1) {
    question = questions[i][0];
    answer = questions[i][1];
    response = prompt(question);
    response = parseInt(response);
if (response === answer) {
   correctAnswers += 1;
   correct.push(question);
  } else {
   wrong.push(question);
 }
}

  for (var i = 0; i < questions.length; i += 1) {
      question = questions[i].question;
      answer = questions[i].answer;
      response = prompt(question);
      response = parseInt(response);
  if (response === answer) {
    correctAnswers += 1;
  } 
}

二维数组和数组对象的实际区别是什么?它会影响运行for循环更快地对数据进行排序吗?我怎么知道哪个更好?

【问题讨论】:

  • 这是一种使用数组的糟糕方式。 questions[i][1] 那是什么? questions[i].answer 其实很有道理。
  • 它以答案元素为目标。任务是回答测验问题......学习JavaScript并被提及

标签: javascript arrays for-loop multidimensional-array


【解决方案1】:

两者的区别很大程度上取决于运行 Javascript 的环境。让我们看看:

http://jsperf.com/array-vs-object-lookup-986

在 chrome V8 中运行它,您可以看到差异是显着的,具有地图查找的优势。对于必须处理您的代码的未来开发人员来说,地图查找表示法也更易于维护。

编辑:地图方式比 FF 快 5 倍。

【讨论】:

    【解决方案2】:

    这里是 es6 中的解决方案:

    var questions = [
      ['How many states are in the United States?', 50],
      ['How many continents are there?', 7],
      ['How many legs does an insect have?', 6]
    ];
    let keys = ["question", "answer"];
    let result = questions.map(r => (keys.reduce((o, k, i) => (o[k] = r[i], o), {})));
    console.log(result)

    【讨论】:

      【解决方案3】:

      在功能上并没有太大区别。数组只是对象的一种特殊类型。数组中的每个索引只是该对象的一个​​属性。所以,二维数组还是对象数组。

      就性能而言,无论哪种方式,您都不应该看到任何明显的影响。

      关于代码的可读性,对象数组方法更清楚每个属性的用途。对于二维数组,没有任何标记每个索引代表什么。仅出于这个原因,我建议在这种情况下使用对象数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-10
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 2016-07-18
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多