How do I check whether an array contains a string in TypeScript?

后端 未结 8 1881
无人及你
无人及你 2020-12-12 11:42

Currently I am using Angular 2.0. I have an array as follows:

var channelArray: Array = [\'one\', \'two\', \'three\'];

How ca

相关标签:
8条回答
  • 2020-12-12 12:13

    Use JavaScript Array includes() Method

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var n = fruits.includes("Mango");
    

    Try it Yourself » link

    Definition

    The includes() method determines whether an array contains a specified element.

    This method returns true if the array contains the element, and false if not.

    0 讨论(0)
  • 2020-12-12 12:20

    TS has many utility methods for arrays which are available via the prototype of Arrays. There are multiple which can achieve this goal but the two most convenient for this purpose are:

    1. Array.indexOf() Takes any value as an argument and then returns the first index at which a given element can be found in the array, or -1 if it is not present.
    2. Array.includes() Takes any value as an argument and then determines whether an array includes a this value. The method returning true if the value is found, otherwise false.

    Example:

    const channelArray: string[] = ['one', 'two', 'three'];
    
    console.log(channelArray.indexOf('three'));      // 2
    console.log(channelArray.indexOf('three') > -1); // true
    console.log(channelArray.indexOf('four') > -1);  // false
    console.log(channelArray.includes('three'));     // true
    
    0 讨论(0)
提交回复
热议问题