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

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

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


当前回答

与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 ()

其他回答

还要注意,“in”关键字对数组不起作用。它只对对象有效。

propName in myObject

数组包含测试为

myArray.includes('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'}]

参考

Array.find ()

Array.some ()

Array.filter ()

你也可以使用滤镜

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

使用JavaScript数组include()方法

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

自己试试»链接

定义

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

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

你可以使用some方法:

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

你可以使用find方法:

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

或者你可以使用indexOf方法:

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