我正在与 prism-react-renderer
合作,它突出显示了我在 MDX 内的 JSX 中渲染的模板字符串。由于间距,这会在使用时导致一些空白:
<Code>
{`
function test() {
return "Test";
};
`}
</Code>
这会导致prism-react-renderer
创建空的第一行和最后一行。如果第一行和最后一行为空,我想删除它们。我正在使用的数组具有以下类型:
type TokenArray = {
types: string[];
content: string;
empty?: boolean;
}[][];
外部数组保存表示线条的数组。这些内部数组包含一个带有 empty
的对象属性(property)。
我想从外部数组 tokenArray
中删除第一个或最后一个项目如果该行的 empty 属性设置为 true。
我尝试过的
使用 tokenArray[0]
查看外部数组的第一项并获取其唯一的项目(如何?)并检查该对象是否具有名为 empty
的属性值为 true
。如果是,请调用tokenArray.shift()
可以对最后一项执行相同的操作,但我不知道如何使用 tokenArray[?]
访问它。
请帮帮我。
最佳答案
如果您想要二维数组中的第一个元素,请使用数组[0][0]。 (就像我们通过数组[行][列]访问)
对于最后一项,它将是
数组[最后一行][最后一列]
最后一行 = 数组[数组.长度 - 1]
最后一行的最后一项 = array[array.length - 1][last_row.length - 1]
这里是 typescript playground 的链接
type TokenArray = {
types: string[];
content: string;
empty?: boolean;
}[][];
const tokens: TokenArray = [
[{ types: ['a', 'b'], content: 'abc', empty: true },
{ types: ['c', 'd'], content: 'cde', empty: false }],
[{ types: ['p', 'q'], content: 'pqr', empty: true },
{ types: ['x', 'y'], content: 'xyz', empty: false }],
];
const first = tokens[0][0];
const last = tokens[tokens.length - 1][tokens[tokens.length - 1].length - 1];
console.log('first', first, "Is Empty true?: ", first.empty === true);
console.log('last', last, "Is Empty true?: ", last.empty === true);
关于javascript - 如果empty = true,则从双层嵌套数组中删除第一个和最后一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119021/