生成值为A1、A2、A3、B1、B2、B3等的数组



我正在尝试生成一个对象数组,它输出的数组如下所示:

[
{
_id: 2,
label: 'A1'
},
{
_id: 3,
label: 'A2'
},
{
_id: 4,
label: 'A3'
},
{
_id: 5,
label: 'B1'
},
{
_id: 6,
label: 'B2'
},
{
_id: 7,
label: 'B3'
}
]

一直到字母";G〃;。。。然而,我似乎无法完全理解如何自动生成它。到目前为止,我已经想出了这个办法,但在我的输出中,它跳过了字母,只是没有正确生成:)可能需要一些帮助。

到目前为止我所拥有的:

function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
const supersetOptions = computed(() => {
const maxGroup = 6;
const maxItems = 12;
let defaultLetter = 'a';
return Array.from({ length: maxItems }, (value, index) => {
const currentLetter = nextChar(defaultLetter)
defaultLetter = nextChar(currentLetter);
return {
label: `${currentLetter}${index + 1}`,
value: `${currentLetter}${index + 1}`
};
});
})

您似乎从2开始_id,但我认为这是一个拼写错误。如果不是,则只使用i+2而不是第8行的i+1

在您所说的想要的内容和您的代码试图生成的内容之间,您也有不同的属性名称。这符合你所说的你想要的。

function generate(count) {
const results = []
for(let i = 0 ; i < count ; i++) {
const letter = String.fromCharCode(65 + (i / 3))
const delta = (i % 3) + 1
results.push({
_id: i+1,
label: `${letter}${delta}`
})
}
return results
}
console.log(generate(21))

您可以在所需的组大小之后增加字母,并用余数进行检查。

const
nextChar = c => (parseInt(c, 36) + 1).toString(36),
computed = () => {
const
maxPerGroup = 3,
maxItems = 12;
let letter = 'a';
return Array.from({ length: maxItems }, (_, index) => {               
const value = `${letter}${index % maxPerGroup + 1}`;
index++;
if (index % maxPerGroup === 0) letter = nextChar(letter);
return { index, value };
});
}
console.log(computed());
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用生成器

function* labels(end) {
for (let i = 0; i <= end; i += 1) {
yield {
_id: i + 1,
label: `${String.fromCharCode(65 + (Math.floor(i / 3) % 26))}${i % 3 + 1}`
}
}
}
for (const item of labels(122)) {
console.log([item._id, item.label])
}

最新更新