如何检查数组中是否包含TypeScript中的字符串? [英] How do I check whether an array contains a string in TypeScript?
问题描述
目前我正在使用Angular 2.0。我有一个如下数组:
Currently I am using Angular 2.0. I have an array as follows:
var channelArray: Array<string> = ['one', 'two', 'three'];
如何检查TypeScript中channelArray是否包含字符串'three'?
How can I check in TypeScript whether the channelArray contains a string 'three'?
推荐答案
与JavaScript相同,使用 Array.prototype.indexOf() :
The same as in JavaScript, using Array.prototype.indexOf():
console.log(channelArray.indexOf('three') > -1);
或使用ECMAScript 6 Array.prototype.includes() :
Or using ECMAScript 6 Array.prototype.includes():
console.log(channelArray.includes('three'));
请注意,您也可以使用如下所示的方法@Nitzan找到一个字符串。但是,对于字符串数组,通常不会这样做,而是对于一个对象数组。那些方法更明智。例如
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'}]
参考
这篇关于如何检查数组中是否包含TypeScript中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!