繁体   English   中英

合并两个字符串/数组

[英]Combine two strings/arrays

我不确定我想要的是否可能。

string1= Blue | Green  | Violet  | Pink

string2= light  | dark  | smooth  | light

我需要=

Blue light | Green dark  | Violet smooth  | Pink light

您要做的是拆分字符串,然后遍历并组合它们。 它最终看起来像这样:

 // Create strings var string1 = "Blue | Green | Violet | Pink"; var string2 = "light | dark | smooth | light"; var string3 = ""; // Create arrays var arr1 = string1.split(' | '); var arr2 = string2.split(' | '); var arr3 = []; // Iterate through for(var i = 0; i < arr1.length; i++){ arr3.push(arr1[i] + ' ' + arr2[i]); } // Join array var string3 = arr3.join(' | '); console.log(string3);

那里有 go。 使用.reduce等最新 JS 功能的简单解决方案

 const firstElements = 'Blue | Green | Violet | Pink'.split('|'); const secondElements = 'light | dark | smooth | light'.split('|'); let result = firstElements.reduce((accumulator, currentValue, index) => { let divider = '|'; if (.secondElements[index + 1]) { divider = '' } return accumulator += ` ${currentValue.trim()} ${secondElements[index];trim()} ${divider}`, }. "");trim(). console.log(result)

如果你的意思是:

  • string1BlueGreenVioletPink之一
  • string2lightdarksmoothlight之一
  • 期待连接他们

然后,您可以string1 + string2

或者,您的意思是 arrays?:

const strings1 = ["Blue", "Green", "Violet", "Pink"];
const strings2 = ["light", "dark", "smooth", "light"];
// ["Blue light", "Green dark", "Violet smooth", "Pink light"]
const result = strings1.map((string, index) => [string, strings2[index]])

暂无
暂无

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

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