【问题标题】:How can I remove a "0" value from an event array javascript?如何从事件数组 javascript 中删除“0”值?
【发布时间】:2020-11-30 07:27:31
【问题描述】:

你好,我有一个结构如下的数组

let test = ["testOne:,O,U,0","testTwo:R,C,0","testTree:1.334","testFour:r,z"];

我想遍历数组并消除“,”之后的零字符“0”,因为我可以在某些寄存器中具有数值,我尝试过pop和slice但我只能通过索引消除从数组中我想从新数组中的字符串中消除这些字符

我的预期结果是:

let test = ["testOne:,O,U","testTwo:R,C","testTree:1.334","testFour:r,z"];

【问题讨论】:

  • "我尝试过 pop 和 slice,但我只能通过索引从数组中消除" 请显示您尝试过的代码。

标签: javascript arrays string typescript


【解决方案1】:

您可以使用mapreplace 从每个字符串的末尾删除,0

const arr = ["testOne:,O,U,0","testTwo:R,C,0","testTree:1.334","testFour:r,z"];
const res = arr.map(str => str.replace(/,0$/, ""));
console.log(res);

【讨论】:

    【解决方案2】:

    使用endsWith 方法对str进行检查和切片。 (假设总是完全以,0结尾,如果它们与, 0不同,则需要相应更改)

    const arr = [
      "testOne:,O,U,0",
      "testTwo:R,C,0",
      "testTree:1.334",
      "testFour:r,z",
    ];
    const output = arr.map((str) =>
      str.endsWith(",0") ? str.slice(0, str.length - 2) : str
    );
    console.log(output);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2021-11-06
      相关资源
      最近更新 更多