Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

javascript - 如何检查数组中是否包含TypeScript中的字符串?(How do I check whether an array contains a string in TypeScript?)

Currently I am using Angular 2.0.(目前我正在使用Angular 2.0。)

I have an array as follows:(我有一个数组如下:) var channelArray: Array<string> = ['one', 'two', 'three']; How can I check in TypeScript whether the channelArray contains a string 'three'?(如何在TypeScript中检查channelArray是否包含字符串'three'?)   ask by code1 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The same as in JavaScript, using Array.prototype.indexOf() :(与JavaScript相同,使用Array.prototype.indexOf() :)

console.log(channelArray.indexOf('three') > -1); Or using ECMAScript 2016 Array.prototype.includes() :(或者使用ECMAScript 2016 Array.prototype.includes() :) console.log(channelArray.includes('three')); Note that you could also use methods like showed by @Nitzan to find a string.(请注意,您还可以使用@Nitzan显示的方法来查找字符串。) However you wouldn't usually do that for a string array, but rather for an array of objects.(但是,对于字符串数组,通常不会这样做,而是对于一个对象数组。) There those methods were more sensible.(那些方法更明智。) For example(例如) 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'}] Reference(参考) Array.find()(Array.find()) Array.some()(Array.some()) Array.filter()(Array.filter())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...