目前我正在使用 Angular 2.0。我有一个数组如下:
var channelArray: Array<string> = ['one', 'two', 'three'];
如何在 TypeScript 中检查 channelArray 是否包含字符串“三”?
channelArray: string[]
与 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'}]
参考
您可以使用 some method:
console.log(channelArray.some(x => x === "three")); // true
您可以使用 find method:
console.log(channelArray.find(x => x === "three")); // three
或者您可以使用 indexOf method:
console.log(channelArray.indexOf("three")); // 2
如果您的代码基于 ES7(或更高版本):
channelArray.includes('three'); //will return true or false
如果没有,例如您使用的是没有 babel 转译的 IE:
channelArray.indexOf('three') !== -1; //will return true or false
indexOf
方法将返回元素在数组中的位置,因为如果在第一个位置找到针,我们使用与 -1 不同的 !==
。
另请注意,"in" keyword 不适用于数组。它仅适用于对象。
propName in myObject
数组包含测试是
myArray.includes('three');
使用 JavaScript 数组 includes() 方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
亲自尝试 » link
定义
includes() 方法确定数组是否包含指定元素。
如果数组包含元素,则此方法返回 true,否则返回 false。
TS 有许多用于数组的实用方法,可通过 Arrays 的原型获得。有多种方法可以实现这个目标,但最方便的两个是:
Array.indexOf() 将任何值作为参数,然后返回可以在数组中找到给定元素的第一个索引,如果不存在则返回 -1。 Array.includes() 将任意值作为参数,然后判断数组是否包含 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
您也可以使用 filter
this.products = array_products.filter((x) => x.Name.includes("ABC"))
这样做:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
不定期副业成功案例分享
[ts] Property 'includes' does not exist on type 'string[]'
错误,我需要更新我的 tsconfig 以支持这个 ecma 6 功能吗?"lib": ["es7", "dom"]