例如:
我有一个数组
const tags = ['size-1', 'size-2', 'discount-xyz']在本例中,为了检查是否有带有折扣的子字符串,我已将数组转换为字符串。
const arrayToString = tags.toString();产出:
const tagsArrayToString = size-1,size-2,discount-wyx;我用这样的if语句来检查:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }到目前一切尚好。但是我如何获得像"discount-xyz"这样的完整字符串
发布于 2021-01-18 21:33:11
我不会将tags数组转换为字符串--您已经将字符串很好地分开了,这只会使事情变得更加困难。
相反,您可以使用filter数组:
const filteredTags = tags.filter(t => t.includes('discount'));或者,如果您知道只有一个这样的字符串,您可以使用find获得它:
const relevantTag = tags.find(t => t.includes('discount'));发布于 2021-01-18 21:34:08
使用findIndex方法查找折扣标签的索引,然后通过数组的索引查找标记本身。
const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];https://stackoverflow.com/questions/65782278
复制相似问题