繁体   English   中英

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

[英]How do I check whether an array contains a string in TypeScript?

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

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

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

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

Array.filter()

您可以使用一些方法

console.log(channelArray.some(x => x === "three")); // true

您可以使用查找方法

console.log(channelArray.find(x => x === "three")); // three

或者您可以使用indexOf 方法

console.log(channelArray.indexOf("three")); // 2

另请注意, “in”关键字不适用于数组。 它仅适用于对象。

propName in myObject

数组包含测试是

myArray.includes('three');

使用JavaScript Array includes()方法

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

自己尝试 » 链接

定义

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

如果数组包含元素,则此方法返回 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 不同。

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

  1. Array.indexOf()任何值作为参数,然后返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回 -1。
  2. 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;
    }

使用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

\n
\n
\n
if([2,3,369,634,655].indexOf(p.id) <0 ) {continue;}
\n
\n
\n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM