在Javascript中声明和填充多维数组的有效方法 [英] Efficient way to declare and populate multidimensional array in Javascript

查看:58
本文介绍了在Javascript中声明和填充多维数组的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中声明和填充多维数组的最有效方法是什么?

What's the most efficient way to declare and populate a multidimensional array in JavaScript?

我目前正在这样做:

ff = Array();
for (i = 0; i < 30; i++) {
    ff[i] = Array();
    ff[i][i] = 1.0;
}

ff[1][2] = 0.041666667;
ff[1][3] = 0.000694444;
ff[2][3] = 0.016666667;
ff[1][4] = 0.000011574;
ff[2][4] = 0.000277778;
ff[3][4] = 0.016666667;
ff[1][5] = 0.000011574;
ff[2][5] = 0.000035315;
ff[3][5] = 0.00211888;
ff[4][5] = 0.1271328;
ff[1][6] = 0.000000025;
ff[2][6] = 0.000000589;
ff[3][6] = 0.000035315;
ff[4][6] = 0.00211888;
ff[5][6] = 0.016666667;

最高 ff [n] [n] 其中 n 最多可以达到30,这导致数百行声明数组值(这是否重要,即使缩小了?)。我只需要填充数组的顶部一半,因为 ff [n] [n] = 1 ff [i] [j] = 1 /(ff [j] [i])所以在声明之后我遍历整个数组并反转顶部一半以填充底部一半。

up to ff[n][n] where n can be up to 30, which leads to hundreds of lines of declaring array values (does this matter, even when minified?). I only need to populate the "top" half of the array since ff[n][n] = 1 and ff[i][j] = 1/(ff[j][i]) so after the declaration I loop over the whole array and invert the "top" half to populate the "bottom" half.

推荐答案

从查看您的数字看,您似乎正在尝试在不同的时间单位之间进行转换。

From looking at your numbers, it looks like you're trying to convert between various time units.

我想知道更合适是不是一个对象。

I wonder if a better fit wouldn't be an object.

var seconds = {
  day:   86400,
  hour:   3600,
  minute:   60,
  second:    1
};

var conversions = {};

['day','minute','hour','second'].forEach(function(fromUnit){
  var subConversions = {};
  var fromValue = seconds[fromUnit];
  ['day','minute','hour','second'].forEach(function(toUnit){
    subConversions[toUnit] = fromValue / seconds[toUnit];
  });
  conversions[fromUnit] = subConversions;
});

function convert(value, from, to){
  return value * conversions[from][to];
}

这将给你。


convert(1,'day','hour')=== 24

convert(1, 'day','hour') === 24

convert(1,'day', 'second')=== 86400

convert(1, 'day','second') === 86400

转换(3,'小时','秒')=== 10800

convert(3, 'hour','second') === 10800

即使事情比简单的时间转换更复杂,这种方法可能会导致更容易理解的代码。一旦你开始给出多维数组元素的特殊含义,事情就会变得非常难看。

Even if things are more complicated than simple time conversion, this approach is probably going to lead to much more understandable code. Once you start giving the elements of a multi-dimensional array special meanings, things can get pretty ugly.

这篇关于在Javascript中声明和填充多维数组的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆