有没有一种简单的方法来创建一个 javascript 查找表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9006111/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:22:30  来源:igfitidea点击:

Is there a simple way to create a javascript lookup table?

javascriptlookup-tables

提问by Paul

I'm looking for a simple way of looking up a value, using javascript, against a number of dimensions:

我正在寻找一种使用 javascript 针对多个维度查找值的简单方法:

eg. (I'm going to use products and product options to describe this, the data is coming from a database in a very similar format)

例如。(我将使用产品和产品选项来描述这一点,数据来自格式非常相似的数据库)

Colour  Size Price

Blue    S    £45

Blue    L    £98

Red     S    £65

Red     L    £31

So I then have a number of dropdowns on the page

所以我然后在页面上有一些下拉菜单

Colour: Blue, Red

Size:   Small, Large

So - I want to know...given "Blue + Small", what the price is

所以 - 我想知道...给定“蓝色 + 小号”,价格是多少

I have no idea what order the dropdowns are in, or the order in which Colour and Size are pulled from the database

我不知道下拉菜单的顺序,或者从数据库中提取颜色和尺寸的顺序

The data in javascript may be an array like this:

javascript 中的数据可能是这样的数组:

{Colour:Blue, Size:Medium, Price:48},{Colour:Blue, Size:Large, Price:82}

It's a crude example, but I can't work out an easy way to achieve this in javascript.

这是一个粗略的例子,但我无法在javascript中找到一种简单的方法来实现这一点。

回答by Nuno Rafael Figueiredo

You can index prices in a two dimensional map on page load (with working fiddle).

您可以在页面加载时在二维地图中索引价格(使用工作小提琴)。

1) I put the select values in lookup-tables in case you have to preload them:

1)我将选择值放在查找表中,以防您必须预加载它们:

var tables = {
    Colour: ["Blue", "Red"],
    Size: ["Small", "Medium", "Large"]
};

2) Here is your price table in array form:

2)这是您的数组形式的价格表:

var array = [
    {Colour: "Blue", Size: "Small", Price: 45},
    {Colour: "Blue", Size: "Medium", Price: 48},
    {Colour: "Blue", Size: "Large", Price: 98},
    {Colour: "Red", Size: "Small", Price: 65},
    {Colour: "Red", Size: "Large", Price: 31}
];

3) Initializing selects (populating values and event 'change'):

3) 初始化选择(填充值和事件 'change'):

for (var key in tables)
    if (tables.hasOwnProperty(key)) {
        selects[key] = form[key];
        selects[key].addEventListener("change", updateSpan);

        var values = tables[key];
        len = values.length;
        for (i = 0; i < len; i++) {
            var option = document.createElement('option');
            option.appendChild(document.createTextNode(values[i]));
            form[key].appendChild(option);
        }
    }

4) Indexing your price table:

4)索引您的价格表:

len = array.length;
for (i = 0; i < len; i++) {
    var record = array[i];

    if (typeof map[record.Colour] === 'undefined')
        map[record.Colour] = {};

    map[record.Colour][record.Size] = record.Price;
}

5) Function updateSpan (on select change):

5) 函数 updateSpan(选择更改时):

function updateSpan() {
    var Colour = selects.Colour.options[selects.Colour.selectedIndex].value;
    var Size = selects.Size.options[selects.Size.selectedIndex].value;

    if (typeof map[Colour] !== 'undefined' && typeof map[Colour][Size] !== 'undefined')
        span.textContent = map[Colour][Size];
    else
        span.textContent = "Price not defined to Colour: " + Colour + " and Size: " + Size + ".";
}

6) Debugging (hit F12 in Chrome or Firefox to open Console View).

6) 调试(在 Chrome 或 Firefox 中按 F12 打开控制台视图)。

Full indexed table:

完整索引表:

console.log(map);

Just the price of 'Blue' & 'Small':

只是“蓝色”和“小”的价格:

console.log(map['Blue']['Small']); // outputs the value: 45

回答by Yoshi

This maybe?

这也许?

var data = {
  1: {
    2: {
      3: 45
    }
  },
  2: {
    2: {
      3: 98
    }
  }
};

console.log(data[1][2][3]); // 45
console.log(data[2][2][3]); // 98

// or
var A = 1, B = 2, C = 3;
console.log(data[A][B][C]); // still 45

回答by hugomg

The most common solution to this is just looping over the array, in O(N) style.

对此最常见的解决方案是以 O(N) 样式遍历数组。

var filter = {Colour: 'blue', Size:'small'};
function matches_filter(filter, item){
    //you can also have variations on this function that
    //allow for functions, regexes or anything you like in the filter...
    for(var key in filter){
        if Object.prototype.hasOwnProperty.call(filter, key){
            if(item[key] !== filter[key]){
                return false;
            }
        }
    }
    return true;
}

var filtered_items = [];
for(var i=0; i<items.length; i++){
    var item = items[i];
    if(matches_filter(filter, item)){
        filtered_items.push(item);
    }
}

The reasoning behind the brute forcing is that if you have a data set that is large enough to require a better algorithm then there is a good chance it would be best to just send the query back to the server and have its database do the hard work for you.

暴力破解背后的原因是,如果您有一个足够大的数据集需要更好的算法,那么最好将查询发送回服务器并让其数据库完成繁重的工作为你。

For a more complete example you can check this codefrom the Dojo toolkit.

有关更完整的示例,您可以从 Dojo 工具包中查看此代码

回答by E V N Raja

Since the Color + Size is representing the price we can create a enum for color and size separately by provide the index values as follows:

由于颜色 + 尺寸代表价格,我们可以通过提供如下索引值来分别创建颜色和尺寸的枚举:

const color = {
  BLUE: 0,
  RED: 1    
}
const size = {
  SMALL : 0,
  LARGE : 1
}

Value assignments:

var prices[10][2];

prices[color.BLUE][size.SMALL] = 40;
prices[color.BLUE][size.LARGE] = 80;