我使用 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
的数组,您可以:
替换您的
Foo
实例上的数组:instanceOfFoo.items = splitted;
或
将这些添加到您的项目中(例如,如果您可能多次使用相同的
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);
旁注:您的方法中缺少 let
或 const
(我假设这是一种方法,因为缺少 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/