cod*_*de1 209 javascript arrays typescript
目前我正在使用Angular 2.0.我有一个数组如下:
var channelArray: Array<string> = ['one', 'two', 'three'];
Run Code Online (Sandbox Code Playgroud)
如何在TypeScript中检查channelArray是否包含字符串'three'?
chr*_*con 413
与JavaScript相同,使用Array.prototype.indexOf():
console.log(channelArray.indexOf('three') > -1);
Run Code Online (Sandbox Code Playgroud)
或者使用ECMAScript 6 Array.prototype.includes():
console.log(channelArray.includes('three'));
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以使用@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'}]
Run Code Online (Sandbox Code Playgroud)
参考
Nit*_*mer 109
你可以使用一些方法:
console.log(channelArray.some(x => x === "three")); // true
Run Code Online (Sandbox Code Playgroud)
您可以使用find方法:
console.log(channelArray.find(x => x === "three")); // three
Run Code Online (Sandbox Code Playgroud)
或者您可以使用indexOf方法:
console.log(channelArray.indexOf("three")); // 2
Run Code Online (Sandbox Code Playgroud)
Dav*_*han 20
另请注意,“in”关键字 不适用于数组。它仅适用于对象。
propName in myObject
Run Code Online (Sandbox Code Playgroud)
数组包含测试是
myArray.includes('three');
Run Code Online (Sandbox Code Playgroud)
Bas*_*asi 17
使用JavaScript Array includes()方法
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
Run Code Online (Sandbox Code Playgroud)
自己尝试 »链接
定义
在包括()方法确定阵列是否包含指定的元素。
如果数组包含元素,则此方法返回 true,否则返回 false。
TS 有许多用于数组的实用方法,可以通过数组原型获得。有多种方法可以实现此目标,但最方便的两个是:
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
Run Code Online (Sandbox Code Playgroud)
如果您的代码基于ES7:
channelArray.includes('three'); //will return true or false
Run Code Online (Sandbox Code Playgroud)
如果没有,例如,您正在使用没有babel转换的IE:
channelArray.indexOf('three') !== -1; //will return true or false
Run Code Online (Sandbox Code Playgroud)
该indexOf
方法将返回元素在数组中的位置,因为!==
如果在第一个位置找到针,我们将使用不同于-1的位置。
filter
你也 可以使用
this.products = array_products.filter((x) => x.Name.includes("ABC"))
Run Code Online (Sandbox Code Playgroud)