在 JavaScript 变量中存储数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4471869/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store a table of data in a JavaScript variable
提问by Ricket
I am making a special "calculator" which accepts user input and looks up data in a table to find a result. But I'm having trouble with how best to do this, to avoid tons and tons of if statements.
我正在制作一个特殊的“计算器”,它接受用户输入并在表中查找数据以找到结果。但是我在如何最好地做到这一点上遇到了麻烦,以避免大量的 if 语句。
As an example, say there are some sets of radio buttons, and each combination of buttons has a unique value which I want to show the user. What sort of data structure would I use in JavaScript to account for each combination of buttons and look up the corresponding value?
例如,假设有几组单选按钮,并且每个按钮组合都有一个唯一的值,我想向用户显示该值。我会在 JavaScript 中使用什么样的数据结构来解释每个按钮组合并查找相应的值?
Edit: upon request, here is some example data:
编辑:根据要求,这里是一些示例数据:
| Type  | Color  | Output value |
| small | red    | 21.9         |
| small | blue   | 27.3         |
| small | yellow | 26.8         |
| large | red    | 19.2         |
...
The user is then presented with two radio sets or dropdowns, one for type and one for color. Upon choosing the combination and pressing the button, the output value is shown.
然后向用户呈现两个单选框或下拉列表,一个用于类型,另一个用于颜色。选择组合并按下按钮后,将显示输出值。
In my specific case I have a table with 4 different columns and many combinations. It looks like an array will do, but if it's an array of objects then I have to type the column names on every row (i.e.: {type: 'small', color: 'red', output: 21.9}, ...) -- is there a way to keep the associative nature of objects with the compact array syntax such as ['small','red',21.9]?
在我的特定情况下,我有一个包含 4 个不同列和许多组合的表。它看起来像一个数组,但如果它是一个对象数组,那么我必须在每一行上键入列名(即:{type: 'small', color: 'red', output: 21.9}, ...)——有没有办法用紧凑数组语法保持对象的关联性,例如['small','red',21.9]?
回答by David Tang
Something like this?
像这样的东西?
var table = [
   ["High", 1, 2, 1, 0],
   ["Medium", 0, 1, 3, 2],
   ...
]
The first element in each array is the result of your "calculator"; the subsequent ones represent the selected indices of each set of radio buttons (though they could be the radio buttons' values too).
每个数组中的第一个元素是“计算器”的结果;随后的代表每组单选按钮的选定索引(尽管它们也可以是单选按钮的值)。
So say the user selects these radio buttons:
假设用户选择了这些单选按钮:
var selection = [0, 1, 3, 2];
Then iterate through the table, slicing each "row" to exclude the first element, and doing an array compare with selection:
然后遍历 ,对table每个“行”进行切片以排除第一个元素,并与 进行数组比较selection:
for (var i = 0, row; row = table[i]; i++) {
    var sRow = row.slice(1);
    // Array compare sRow and selection (function arrayEqual not included)
    if (arrayEqual(sRow, selection)) {
        return row[0];
    }
}
// Will return "Medium"
Update:Using the poster's example data, the table would look like:
更新:使用海报的示例数据,表格将如下所示:
var table = [
   [21.9, "small", "red"],
   [27.3, "small", "blue"],
   ...
]
回答by Felix Kling
Maybe not be the best solution in terms of memory but very fast to look up, would be a lookup table like so:
可能不是内存方面的最佳解决方案,但查找速度非常快,将是一个如下所示的查找表:
var table = {
    'small': {
        'red': ...,
        'blue': ...
    },
    'large': {
        'red': ...,
        'blue':...
    },
    ...
}
Then you could access a value with just:
然后你可以访问一个值:
var value = table[type][color]
The drawback is that you have to repeat a lot of properties. But if you have not so many different values then this would be ok I think.
缺点是你必须重复很多属性。但是,如果您没有那么多不同的值,那么我认为这没问题。
If you want to save memory, the best way would be to figure out some formula, assign numbers to your text values and compute the values on the fly (and cache the results).
如果您想节省内存,最好的方法是找出一些公式,为文本值分配数字并动态计算值(并缓存结果)。
回答by Spiny Norman
An object, I guess?
一个对象,我猜?
var states = {
    state1: value1,
    state2: value2,
    state3: value3,
    (etc)
}
回答by g.d.d.c
Well, we're working with JavaScript, so your choices are Arrays and Objects. The key factor determining which you should use is probably based on how you want to look things up. Arrays will have numeric indexes and must be sequential starting at 0, while Objects use Strings as their indexes (keys) and can contain anything you want them to.
好吧,我们正在使用 JavaScript,所以您的选择是数组和对象。决定您应该使用哪个的关键因素可能取决于您希望如何查找。数组将具有数字索引,并且必须从 0 开始按顺序排列,而对象使用字符串作为它们的索引(键),并且可以包含您希望它们包含的任何内容。
If you're interested in a database-like library of sorts for JavaScript I'd look at TaffyDB. It allows you to query collections by passing in objects that represent the conditions that determine what you want returned.
如果您对 JavaScript 的类似数据库的库感兴趣,我会查看 TaffyDB。它允许您通过传入表示确定您想要返回的内容的条件的对象来查询集合。
回答by user187291
A better option might be to keep the table in a string form, just like you've posted it:
更好的选择可能是将表格保留为字符串形式,就像您发布的那样:
table = 
    " small  red     21.9" +
    " small  blue    27.3" +
    " small  yellow  26.8" +
    " large  red     19.2"
For searching for a specific value you can use regular expressions, for example:
要搜索特定值,您可以使用正则表达式,例如:
function find(type, color) {
   var re = new RegExp("\b" + type + "\s+" + color + "\s+(\S+)", "m");
   var m = table.match(re)
   return m ? m[1] : null;
}
The advantages of this method are 1) the "database" remains readable and easy to maintain 2) regexps will probably be faster than looping through nested arrays.
这种方法的优点是 1) “数据库”保持可读且易于维护 2) 正则表达式可能比循环嵌套数组更快。

