我正在寻找一种使用javascript查找价值的简单方法:
例如。 (我将使用产品和产品选项来描述这一点,数据来自数据库,格式非常相似)
Colour Size Price
Blue S £45
Blue L £98
Red S £65
Red L £31
所以我在页面上有一些下拉列表
Colour: Blue, Red
Size: Small, Large
所以 - 我想知道......给出" Blue + Small",价格是什么
我不知道下拉列表的顺序,或者从数据库中提取颜色和大小的顺序
javascript中的数据可能是这样的数组:
{Colour:Blue, Size:Medium, Price:48},{Colour:Blue, Size:Large, Price:82}
这是一个粗略的例子,但我无法通过简单的方法在javascript中实现这一目标。
答案 0 :(得分:11)
您可以在页面加载时使用二维地图索引价格(使用'Compilers' section)。
1)我将选择值放在查找表中,以防你必须预加载它们:
var tables = {
Colour: ["Blue", "Red"],
Size: ["Small", "Medium", "Large"]
};
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)初始化选择(填充值和事件'更改'):
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)索引价格表:
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)功能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)调试(在Chrome或Firefox中点击F12以打开控制台视图)。
完整索引表:
console.log(map);
只是'蓝'和'的价格'小':
console.log(map['Blue']['Small']); // outputs the value: 45
答案 1 :(得分:7)
这可能吗?
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
答案 2 :(得分:6)
最常见的解决方案是以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);
}
}
粗暴强制背后的原因是,如果你的数据集足够大,需要更好的算法,那么最好将查询发送回服务器并使其数据库更好为你付出的努力。
有关更完整的示例,您可以从Dojo工具包中查看this code。
答案 3 :(得分:0)
由于颜色+尺寸表示价格,因此我们可以通过提供以下索引值来分别创建颜色和尺寸的枚举:
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;