如何在 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 2016 Array.prototype.includes():
Or using ECMAScript 2016 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屋!