Come posso controllare se un array contiene una stringa in TypeScript?

Attualmente sto usando Angular 2.0. Ho un array come segue:

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

Come posso controllare in TypeScript se il channelArray contiene una stringa 'tre'?

Soluzione

Lo stesso che in JavaScript, usando Array.prototype.indexOf():

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

Oppure usando ECMAScript 2016 Array.prototype.includes():

console.log(channelArray.includes('three'));

Notate che potreste anche usare metodi come quello mostrato da @Nitzan per trovare una stringa. Tuttavia di solito non lo faresti per un array di stringhe, ma piuttosto per un array di oggetti. Lì quei metodi erano più sensati. Per esempio

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'}]

Riferimento

Array.find()

Array.some()

Array.filter()

Commentari (2)

Potete usare il qualche metodo:

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

Puoi usare il metodo find:

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

Oppure puoi usare il metodo indexOf:

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

Se il tuo codice è basato su ES7:

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

Se non lo è, per esempio stai usando IE senza babel transpile:

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

il metodo indexOf restituirà la posizione che l'elemento ha nell'array, per questo usiamo !== diverso da -1 se l'ago si trova nella prima posizione.

Commentari (0)