javascript - Typescript - 将拆分后的字符串推送到数组

标签 javascript angular typescript ecmascript-6

我使用 Angular 2 编写了一个应用程序。

我有一个输入,我想输入字符串列表,然后用逗号分隔它们。

输入:Item1、Item2、Item3

输入的字符串我必须用逗号分隔。

addItems(toSplit: string) {
   splitted: string[] = toSplit.split(",");
}

我有一个对象:

export class Foo {
   items: string[];
}

如何将所有拆分后的字符串推送到 foo.items?

最佳答案

And I have an object

那不是一个对象,它是一个类。 (好吧,当然,它也是一个对象。)要访问items,首先你需要一个实例来访问它:

const instanceOfFoo: Foo = new Foo();

然后,一旦您拥有该实例并且您拥有来自 split 的数组,您可以:

  1. 替换您的 Foo 实例上的数组:

    instanceOfFoo.items = splitted;
    

  2. 将这些添加到您的项目中(例如,如果您可能多次使用相同的 Foo 执行此操作):

    instanceOfFoo.items.push(...splitted);
    

    那个 ... 是扩展符号,TypeScript 应该通过转换支持它。如果你想要老式的:

    instanceOfFoo.items.push.apply(instanceOfFoo.items, splitted);
    

如果在创建 Foo 之前 已经有了拆分字符串,则可以将其作为参数提供给构造函数,然后在构造函数中执行其中一项操作,以两者为准更适合您的需要:

// Using the array provided directly
export class Foo {
    constructor(public items: string[] = []) {
    }
}

// Copying the given array
export class Foo {
    public items: string[] = [];
    constructor(items: string[]) {
        this.items.push(...items);
    }
}

然后使用其中任何一个:

const instanceOfFoo: Foo = new Foo(splitted);

旁注:您的方法中缺少 letconst(我假设这是一种方法,因为缺少 function在它前面):

addItems(toSplit: string) {
   const splitted: string[] = toSplit.split(",");
// ^---- here, should be const or let depending on whether you want
// to be able to change it
}

关于javascript - Typescript - 将拆分后的字符串推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44630401/

相关文章:

javascript - 在特定索引处使用 .replace()

c# - asp.net中如何显示消息框

events - Angular 2 - 在(点击)事件中使用管道

arrays - Angular 将 json 转换为对象数组

node.js - 虚拟助手机器人框架和控制库

angularjs - 使用 TypeScript 从页面对象返回 Promise 值

javascript - 如何隐藏#id对象

javascript - 如何将具有多个对象的 JSON 对象转换为一组对象

angular - 是否建议客户端路由与服务器端路由一起提供 angular-universal

javascript - 如何在内存中正确存储访问 token react