我正在寻找一组数组并将它们转换为表对象(或类似表的对象)。在这种情况下,我有一个潜在的 RGB 值列表。
我不关心二维对象的可视化,而只是从中选择和操作。
这是我的开始:一组数组:
["Class", "R", "G", "B"],
["1", "166", "206", "227"],
["2", "31", "120", "180"],
["3", "51", "160", "44"]
然后我希望能够根据列或行来选择内容。我更关心选择元素的方便性,而不是创建 html 对象 (tr/td)。我想根据列标识符(例如 R:“166”、“31”、“51”——)或行标识符(1:“31”、“120”、“180”—— -- 例如)。
Class | R | G | B
1 | 166 | 206 | 227
2 | 31 | 120 | 180
3 | 51 | 160 | 44
这是我的问题:
1. 我要找什么样的对象?
2. 我如何从一系列数组创建它,其中键/表头基于第一个数组(动态分配 - 而不是硬编码)?
我感谢您对此的看法:
大卫
最佳答案
我建议使用对象数组:
var color = [
{ Class: 1, R: 166, G: 206, B: 227 },
{ Class: 2, R: 31, G: 120, B: 180 },
{ Class: 3, R: 51, G: 160, B: 44 }
];
和
var classIndex = {
'1': 0,
'2': 1,
'3': 2
};
用于存储数组项的索引。
通过color[classIndex[1]]['R']
访问
工作示例:
function colorType(cl, r, g, b) {
return { Class: cl, R: r, G: g, B: b };
}
function addColor(ct) {
color.push(ct);
classIndex = {};
color.forEach(function (a, i) { classIndex[a.Class] = i; });
}
function getColorColumn(key) {
return color.map(function (a) { return a[key]; });
}
function updateColorColumn(key, values) {
color.forEach(function (a, i) { a[key] = values[i]; });
}
function changeColumn(key, cb) {
color.forEach(function (a, i) { a[key] = cb(a[key]); });
}
var color = [
{ Class: 1, R: 166, G: 206, B: 227 },
{ Class: 2, R: 31, G: 120, B: 180 },
{ Class: 3, R: 51, G: 160, B: 44 }
],
classIndex = {
'1': 0,
'2': 1,
'3': 2
};
// display a single item
document.write('<pre>color[classIndex[1]][\'R\']: ' + color[classIndex[1]]['R'] + '</pre>');
// display the color array
document.write('<pre>color: ' + JSON.stringify(color, 0, 4) + '</pre>');
// add a new color
addColor(colorType(4, 51, 102, 153));
document.write('<pre>color after insert: ' + JSON.stringify(color, 0, 4) + '</pre>');
document.write('<pre>classIndex after insert: ' + JSON.stringify(classIndex, 0, 4) + '</pre>');
// get column B
var blue = getColorColumn('B');
document.write('<pre>blue: ' + JSON.stringify(blue, 0, 4) + '</pre>');
// change blue
blue = blue.map(function (a) { return Math.min(a * 1.2, 255) | 0; });
document.write('<pre>blue after update: ' + JSON.stringify(blue, 0, 4) + '</pre>');
// update column B with blue
updateColorColumn('B', blue);
document.write('<pre>color after changing B: ' + JSON.stringify(color, 0, 4) + '</pre>');
// change R directly
changeColumn('R', function (v) { return Math.max(v * 0.5, 0) | 0; });
document.write('<pre>color after changing R: ' + JSON.stringify(color, 0, 4) + '</pre>');
关于javascript - 从数组 Javascript 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553020/