如何在 TypeScript 中检查数组是否包含字符串? [英] How do I check whether an array contains a string in TypeScript?

查看:228
本文介绍了如何在 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'}]

参考

Array.find()

Array.some()

Array.filter()

这篇关于如何在 TypeScript 中检查数组是否包含字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆