如何检查数组中是否包含TypeScript中的字符串?

时间:2017-03-14 15:50:27

标签: javascript arrays typescript

目前我正在使用Angular 2.0。我有一个数组如下:

var channelArray: Array<string> = ['one', 'two', 'three'];

如何在TypeScript中检查channelArray是否包含字符串'three'?

8 个答案:

答案 0 :(得分:330)

与JavaScript相同,使用Array.prototype.indexOf()

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

或使用ECMAScript 2016 Array.prototype.includes()

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

请注意,您还可以使用@Nitzan显示的方法来查找字符串。但是,对于字符串数组,您通常不会这样做,而是对于一个对象数组。那些方法更明智。例如

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'}]

参考

Array.find()

Array.some()

Array.filter()

答案 1 :(得分:95)

您可以使用some method

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

您可以使用find method

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

或者您可以使用indexOf method

console.log(channelArray.indexOf("three")); // 2

答案 2 :(得分:4)

如果您的代码基于ES7:

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

例如,如果没有,那么您正在使用没有babel转换的IE:

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

indexOf方法将返回元素在数组中的位置,因为如果在第一个位置找到了针,我们将使用与{-1不同的!==

答案 3 :(得分:3)

您也可以使用filter

this.products = array_products.filter((x) => x.Name.includes("ABC"))

答案 4 :(得分:1)

使用 JavaScript Array includes()方法

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

尝试一下»link

定义

includes()方法确定数组是否包含指定的元素。

如果数组包含元素,则此方法返回true,否则返回false。

答案 5 :(得分:0)

这样做:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }

答案 6 :(得分:0)

还要注意,"in" keyword在数组上不起作用。它仅适用于对象。

propName in myObject

数组包含测试为

myArray.includes('three');

答案 7 :(得分:0)

TS有许多实用的数组方法,可通过Arrays的原型获得。有多种方法可以实现此目标,但最方便的两种方法是:

  1. Array.indexOf()将任何值用作参数,然后返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1。
  2. Array.includes()将任何值用作参数,然后确定数组是否包含this值。如果找到该值,则该方法返回true,否则返回false

示例:

var 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'));     // ture