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

后端 未结 8 1880
无人及你
无人及你 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 11:58

    The same as in JavaScript, using Array.prototype.indexOf():

    console.log(channelArray.indexOf('three') > -1);
    

    Or using ECMAScript 2016 Array.prototype.includes():

    console.log(channelArray.includes('three'));
    

    Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

    const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
    console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
    console.log(arr.some(e => e.foo === 'bar')); // true
    console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]
    

    Reference

    Array.find()

    Array.some()

    Array.filter()

    0 讨论(0)
  • 2020-12-12 11:59

    You can use the some method:

    console.log(channelArray.some(x => x === "three")); // true
    

    You can use the find method:

    console.log(channelArray.find(x => x === "three")); // three
    

    Or you can use the indexOf method:

    console.log(channelArray.indexOf("three")); // 2
    
    0 讨论(0)
  • 2020-12-12 12:01

    If your code is ES7 based:

    channelArray.includes('three'); //will return true or false
    

    If not, for example you are using IE with no babel transpile:

    channelArray.indexOf('three') !== -1; //will return true or false
    

    the indexOf method will return the position the element has into the array, because of that we use !== different from -1 if the needle is found at the first position.

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

    do like this:

    departments: string[]=[];
    if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
                return;
        }
    
    0 讨论(0)
  • 2020-12-12 12:04

    Also note that "in" keyword does not work on arrays. It works on objects only.

    propName in myObject
    

    Array inclusion test is

    myArray.includes('three');
    
    0 讨论(0)
  • 2020-12-12 12:09

    You can use filter too

    this.products = array_products.filter((x) => x.Name.includes("ABC"))
    
    0 讨论(0)
提交回复
热议问题