目前我使用的是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 '?
当前回答
使用JavaScript数组include()方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
自己试试»链接
定义
includes()方法确定数组中是否包含指定元素。
如果数组中包含该元素,则该方法返回true,否则返回false。
其他回答
如果你的代码是基于ES7(或更高版本):
channelArray.includes('three'); //will return true or false
如果不是,例如你正在使用没有babel transpile的IE:
channelArray.indexOf('three') !== -1; //will return true or false
indexOf方法将返回元素在数组中的位置,因为如果在第一个位置找到指针,我们使用的是不同于-1的!==。
这样做:
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([],“两”));/ /错误
你可以使用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
使用JavaScript数组include()方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
自己试试»链接
定义
includes()方法确定数组中是否包含指定元素。
如果数组中包含该元素,则该方法返回true,否则返回false。