我目前使用的是Angular 2.0。我有一个如下的数组:
var channelArray: Array<string> = ['one', 'two', 'three'];
在 TypeScript 中,如何检查 channelArray 是否包含字符串 'three'?
我目前使用的是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'}]
参考资料
[ts] Property 'includes' does not exist on type 'string[]'
错误,我需要更新我的tsconfig以支持这个ECMA 6特性吗? - S.."lib": ["es7", "dom"]
。 - S..如果你的代码是基于ES7或更高版本的:
channelArray.includes('three'); //will return true or false
如果不是这样,比如您正在使用未进行Babel转译的IE:
channelArray.indexOf('three') !== -1; //will return true or false
indexOf
方法返回元素在数组中的位置,因此我们使用 !==
来检查针是否位于第一个位置。
使用 JavaScript 数组 includes() 方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
试一下 » 链接
定义
includes() 方法确定一个数组是否包含指定元素。
如果数组包含该元素,则此方法返回true,否则返回false。
TS有许多针对数组的实用方法,这些方法可以通过Arrays的原型进行访问。虽然有多种方法可以实现此目标,但是最方便的两种方法是:
Array.indexOf()
接受任何值作为参数,并返回给定元素在数组中第一次出现的索引,如果不存在则返回-1。Array.includes()
接受任何值作为参数,并确定数组是否包含此值。如果找到该值,则该方法返回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
您也可以使用过滤器
this.products = array_products.filter((x) => x.Name.includes("ABC"))
像这样做:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
const array = ["one", "two", "three"];
const myArray = (arr, v) => {
return arr.findIndex((item) => item.startsWith(v)) > -1;
};
console.log(myArray(array, "five")); // false
console.log(myArray(array, "two")); // true
console.log(myArray([], "two")); // false
channelArray: string[]
。 - Nitzan Tomer