目前我使用的是Angular 2.0。我有一个数组如下:
var channelArray: Array<string> = ['one', 'two', 'three'];
如何在TypeScript中检查channelArray是否包含字符串' 3 '?
目前我使用的是Angular 2.0。我有一个数组如下:
var channelArray: Array<string> = ['one', 'two', 'three'];
如何在TypeScript中检查channelArray是否包含字符串' 3 '?
当前回答
TS有许多数组的实用方法,这些方法可以通过数组的原型得到。有多种方法可以实现这一目标,但最方便的两种方法是:
array . indexof()接受任意值作为参数,然后返回数组中给定元素所在的第一个下标,如果不存在则返回-1。 include()接受任何值作为参数,然后确定数组是否包含this值。如果找到值,方法返回true,否则返回false。
例子:
const channelArray: string[] = ['one', 'two', 'three'];
console.log(channelArray.indexOf('three')); // 2
console.log(channelArray.indexOf('three') > -1); // true
console.log(channelArray.indexOf('four') > -1); // false
console.log(channelArray.includes('three')); // true
其他回答
TS有许多数组的实用方法,这些方法可以通过数组的原型得到。有多种方法可以实现这一目标,但最方便的两种方法是:
array . indexof()接受任意值作为参数,然后返回数组中给定元素所在的第一个下标,如果不存在则返回-1。 include()接受任何值作为参数,然后确定数组是否包含this值。如果找到值,方法返回true,否则返回false。
例子:
const channelArray: string[] = ['one', 'two', 'three'];
console.log(channelArray.indexOf('three')); // 2
console.log(channelArray.indexOf('three') > -1); // true
console.log(channelArray.indexOf('four') > -1); // false
console.log(channelArray.includes('three')); // true
这样做:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
使用findIndex方法,我们可以获得数组的索引,从而使用startsWith方法实现比较
Const array = ["one", "two", "three"]; const myArray = (arr, v) => { 返回arr.findIndex((item) => item. startswith (v)) > -1; }; console.log (myArray(数组," 5 "));/ /错误 console.log (myArray(数组”,两个“));/ /正确的 console.log (myArray([],“两”));/ /错误
使用JavaScript数组include()方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
自己试试»链接
定义
includes()方法确定数组中是否包含指定元素。
如果数组中包含该元素,则该方法返回true,否则返回false。
你也可以使用滤镜
this.products = array_products.filter((x) => x.Name.includes("ABC"))