programing

배열에 TypeScript 문자열이 포함되어 있는지 확인하려면 어떻게 해야 합니까?

randomtip 2022. 11. 2. 23:20
반응형

배열에 TypeScript 문자열이 포함되어 있는지 확인하려면 어떻게 해야 합니까?

현재 Angular 2.0을 사용하고 있습니다.다음과 같은 어레이가 있습니다.

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

typeScript에서 channelArray에 문자열 '3'이 포함되어 있는지 확인하려면 어떻게 해야 합니까?

JavaScript와 동일하게 Array.protype.indexOf()사용합니다.

console.log(channelArray.indexOf('three') > -1);

또는 ECMAScript 2016 Array.protype.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()

다음과 같은 방법을 사용할 수 있습니다.

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

다음 검색 방법을 사용할 수 있습니다.

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

또는 indexOf 메서드를 사용할 수 있습니다.

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는 method를 사용하기 가 배열로합니다.★★★★★★★★★★★★★★★★★★,!==바늘이 첫 번째 위치에 있는 경우 -1과 다릅니다.

, 「in」키워드는 어레이에서는 동작하지 않습니다.오브젝트에서만 동작합니다.

propName in myObject

어레이 포함 테스트:

myArray.includes('three');

JavaScript Array includes() 메서드 사용

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

Try It Yourself » 링크

정의.

includes() 메서드는 배열에 지정된 요소가 포함되어 있는지 여부를 결정합니다.

이 메서드는 배열에 요소가 포함되어 있으면 true를 반환하고 포함되지 않으면 false를 반환합니다.

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

하시면 됩니다.filter 무 too

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

다음과 같이 합니다.

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

언급URL : https://stackoverflow.com/questions/42790602/how-do-i-check-whether-an-array-contains-a-string-in-typescript

반응형