在JavaScript中将二维数组转换为数组对象

时间:2015-04-16 04:35:20

标签: javascript arrays for-loop multidimensional-array

我有以下二维数组代码

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;
  } 
}

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

3 个答案:

答案 0 :(得分:1)

两者之间的差异很大程度上取决于运行Javascript的环境。让我们看看:

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

在chrome V8中运行它,你可以看到差异是值得注意的,边缘到地图查找。对于必须处理代码的未来开发人员来说,地图查找符号也更加易于维护。

编辑:地图方式的速度提高了5倍。

答案 1 :(得分:1)

这是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)

答案 2 :(得分:0)

功能上,差别不大。数组只是一种特殊类型的Object。数组中的每个索引只是该对象的一个​​属性。因此,二维数组仍然是一个对象数组。

在性能方面,你不应该看到任何明显的影响。

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