简体   繁体   English

如何在数组中的字符串之间插入单词?

[英]How to insert word between string in array?

I have such a data structure:我有这样一个数据结构:

const array = ["item", "item1", "item2", "item4"]

items can be different number.项目可以是不同的数量。 I need to convert this data into "item" OR "item1" OR "item2" OR "item4" I used lodash join() but it gives me string "item OR item1 OR item2 OR item4" and this is not what I need.我需要将此数据转换为“item”或“item1”或“item2”或“item4”,我使用了lodash join(),但它给了我字符串“item OR item1 OR item2 OR item4”,这不是我需要的。 How can I receive such a structure "item" OR "item1" OR "item2" OR "item4 from an array?如何从数组中接收这样的结构"item" OR "item1" OR "item2" OR "item4

Use join() and wrap result with extra "使用join()并用额外的"包裹结果"

 const array = ["item", "item1", "item2", "item4"] console.log('"' + array.join('" OR "') + '"')

map over the elements to return them as quoted strings (here using a template literal ), then join them: map元素以将它们作为带引号的字符串返回(这里使用模板文字),然后join它们:

 const array = ["item", "item1", "item2", "item4"]; const str = array.map(el => `"${el}"`).join(' OR '); console.log(str);

You could use stringify the items and join with ' OR ' .您可以使用字符串化项目并使用' OR '

 const array = ["item", "item1", "item2", "item4"], string = array.map(o => JSON.stringify(o)).join(' OR '); console.log(string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM