目前我正在使用Angular 2.0。我有一个数组,如下所示。
var channelArray: Array<string> = ['one', 'two', 'three'];
我怎样才能在TypeScript中检查channelArray是否包含一个字符串'three'?
和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'}]
参考资料
如果你的代码是基于ES7的。
channelArray.includes('three'); //will return true or false
如果不是,例如你使用的是没有babel转码的IE。
channelArray.indexOf('three') !== -1; //will return true or false
indexOf
方法将返回元素在数组中的位置,因此,如果在第一个位置找到针,我们使用!==
与-1不同。