【问题标题】:Split Input Array Values - Angular拆分输入数组值 - Angular
【发布时间】:2020-10-22 23:40:45
【问题描述】:

我有一个输入字段,用户可以在其中输入多个输入,其中 comma 介于两者之间。

<div class="container">
    
    Enter your values:<input type="text" multiple #inputCheck>
    <input type="submit"(click)="sendInput(inputCheck.value)">

</div>

这些输入将存储在以下数组中。

 arrayStored=[]

我尝试使用下面的代码,但输入没有在数组中划分,整个输入被视为数组中的单个元素。我需要将输入分成多个元素并将它们存储在数组中。

     sendInput(event:any){
     this.inputGiven = event;
     this.arrayStored.push(this.inputGiven);

示例:如果用户输入SAM,ALEX7,23 并单击提交,则数组应将其存储为arrayStored=["SAM","ALEX7,"23"],但现在将其存储为arrayStored=["SAM,ALEX7,23"]。如何拆分输入并将它们作为单个元素存储在数组中?

【问题讨论】:

  • 试试this.arrayStored = [...this.arrayStored, ...this.inputGiven.split(",")];
  • 它有效,但现在,如果我再次单击提交按钮,它会复制数组内的值。示例:["SAM","ALEX7​​,"23","SAM","ALEX7​​,"23"] 即使多次单击提交按钮,我也需要这些值只出现一次。请问有什么想法吗?
  • 那就试试这个吧。 this.inputGiven.split(",").forEach(value =&gt; { !this.arrayStored.includes(value) &amp;&amp; this.arrayStored.push(value) });
  • forEach(...) is not iterable (cannnot read propery undefiined) 没用。
  • 它未经测试。不管怎样,你得到了答案。

标签: javascript html arrays angular typescript


【解决方案1】:

您可以像这样拆分数组中的元素:

 this.arrayStored.concat(this.inputGiven.spilt(“,”));

要从数组中删除任何重复项,您可以将其转换为一个集合并返回一个数组,如下所示:

 this.arrayStored = Array.from(new Set(this.arrayStored));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 2019-03-26
    相关资源
    最近更新 更多