【问题标题】:Removing first and last item from double nested array if empty = true如果empty = true,则从双嵌套数组中删除第一项和最后一项
【发布时间】:2020-07-21 22:43:35
【问题描述】:

我正在使用prism-react-renderer,它突出显示了我在 MDX 中的 JSX 中呈现的模板字符串。由于间距,这会在使用时产生一些空白:

<Code>
{`
function test() {
    return "Test";
};
`}
</Code>

这会导致prism-react-renderer 创建一个空的第一行和最后一行。如果它们为空,我想删除这些第一行和最后一行。我正在使用的数组具有以下类型:

type TokenArray = {
  types: string[];
  content: string;
  empty?: boolean;
}[][];

外部数组包含表示线条的数组。这些内部数组包含一个具有empty 属性的对象。 如果该行的空属性设置为 true,我想从外部数组 tokenArray 中删除第一项或最后一项。

我的尝试

查看带有tokenArray[0] 的外部数组的第一项并获取其唯一项(如何?)并检查该对象是否具有名为empty 且值为true 的属性。如果有,请致电tokenArray.shift() 最后一项也可以这样做,但我不知道如何使用tokenArray[?] 访问它。

请帮帮我。

【问题讨论】:

    标签: javascript arrays typescript data-structures


    【解决方案1】:

    如果你想要二维数组中的第一个元素,那么使用数组[0][0]。 (就像我们通过 array[row][column] 访问一样)

    对于最后一项,它将是

    数组[最后一行][最后一列]
    last_row = 数组[array.length - 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 2017-05-27
      • 2022-06-25
      • 2021-12-02
      相关资源
      最近更新 更多