ChatGPT解决这个技术问题 Extra ChatGPT

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

目前我正在使用 Angular 2.0。我有一个数组如下:

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

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

它应该是 channelArray: string[]
这不是 Typescript 特定的
@NitzanTomer 他们不一样吗? stackoverflow.com/questions/38239579/…

b
baao

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


我收到 [ts] Property 'includes' does not exist on type 'string[]' 错误,我需要更新我的 tsconfig 以支持这个 ecma 6 功能吗?
弄清楚了。我需要在我的 tsconfig.json 文件中将“es7”添加到属性“lib”的数组中,例如。 "lib": ["es7", "dom"]
N
Nitzan Tomer

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

a
alejoko

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

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

如果没有,例如您使用的是没有 babel 转译的 IE:

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

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


D
David Dehghan

另请注意,"in" keyword 不适用于数组。它仅适用于对象。

propName in myObject

数组包含测试是

myArray.includes('three');

这是一个值得一提的陷阱,特别是如果您来自 Python。更糟糕的是,它在某种程度上也适用于数组,因为它们也是对象。我只是没有按照您可能认为的方式工作 - 它检查数组中是否存在某些东西作为索引。
B
Basi

使用 JavaScript 数组 includes() 方法

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

亲自尝试 » link

定义

includes() 方法确定数组是否包含指定元素。

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


C
Community

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

R
R15

您也可以使用 filter

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

A
Abdus Salam Azad

这样做:

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