如何在TypeScript中检查数组是否包含字符串?

uqxowvwt  于 2023-01-27  发布在  TypeScript
关注(0)|答案(9)|浏览(1669)

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

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

如何在TypeScript中检查channelArray是否包含字符串“three”?

72qzrwbm

72qzrwbm1#

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

q5iwbnjs

q5iwbnjs2#

您可以使用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
qncylg1j

qncylg1j3#

如果您的代码基于ES 7(或更高版本):

channelArray.includes('three'); //will return true or false

如果没有,例如您使用的IE没有babel transpile:

channelArray.indexOf('three') !== -1; //will return true or false

indexOf方法将返回元素在数组中的位置,因为如果指针在第一个位置,我们使用不同于-1的!==

bogh5gae

bogh5gae4#

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

propName in myObject

数组包含测试为

myArray.includes('three');
rdrgkggo

rdrgkggo5#

使用**JavaScript数组包含()**方法

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

自己试试看link

定义
**include()**方法确定数组是否包含指定的元素。

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

h43kikqp

h43kikqp6#

TS有许多数组的实用方法,可以通过数组原型获得。有多种方法可以实现这一目标,但最方便的两种方法是:

  1. Array.indexOf()接受任意值作为参数,然后返回给定元素在数组中的第一个索引,如果不存在,则返回-1。
  2. 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
8wtpewkr

8wtpewkr7#

您也可以使用filter

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

pdtvr36n8#

这样做:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }
fwzugrvs

fwzugrvs9#

使用findIndex方法,我们可以获得数组的索引,从而使用startsWith方法实现比较

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

相关问题