0

As a newbie to SPFx, how do I create and use an array? everything I've tried fails to populate the array.

let CustomerList: Array<any> = ['1', '2', '3'];

let array1: any = ["Panda", "Zebra", "Lion", "Cat", "Dog", "Fish", "whatever", "Bird"];

const foo:string[] = [];

1 Answer 1

0

TomB,

It can be quite daunting to learn the array syntax, especially since many examples out there show older code syntax.

It really depends on where in your code you're defining the arrays.

If you're doing it within a method, you'll probably want to use this syntax:

  public render(): React.ReactElement<IHelloWorldProps> {
    const customerList: Array<string> = ['1', '2', '3'];
    const array1: any = ["Panda", "Zebra", "Lion", "Cat", "Dog", "Fish", "whatever", "Bird"];
    const foo:string[] = [];
...
}

You can use `const` or `let`, but the convention is to use `const` for variables that won't be changed once defined, and `let` for those that will be changed during the life of the variable.

If you're defining the arrays within a class, you probably would want to use the following syntax:

```Typescript
export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {

  private customerList: Array<string> = ['1', '2', '3'];
  private array1: any = ["Panda", "Zebra", "Lion", "Cat", "Dog", "Fish", "whatever", "Bird"];
  private foo:string[] = [];
...
}

(Ignoring naming convention rules for simplicity)

If you want to define the arrays at the module level (e.g.: outside the scope of a class), you once again would use:

const customerList: Array<string> = ['1', '2', '3'];
const array1: any = ["Panda", "Zebra", "Lion", "Cat", "Dog", "Fish", "whatever", "Bird"];
const foo:string[] = [];

Note that I used Array<string> in my examples above instead of an implied any because more and more tslint rules discourage using any. Likewise, I'd suggest you change your array1 to Array<string> or string[] for the same reasons.

I hope this helps?

1
  • Thank you for the quick response, I'm and old C++ guy moving on in this world. This helps a ton, Thank you. on a separate array question, what it the proper syntax for using the array.indexof() to find an element in a list object array? var result = items.filter(obj => { return obj.title === 'test'})
    – TomB
    Commented Jun 9, 2019 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.