当自定义 Javascript 数组是数组中字符串值的组件时,从该数组中提取值

我希望从这个自定义javascript数组中提取值“adult”和“2ndclass”,每个值都有单独的javascript变量。有人对如何做到这一点有任何想法吗?


在以下情况下,有2种产品添加到购物车,但我希望能够灵活地始终获取添加到购物车的每个产品的任何现有值,而不管添加的数量如何。这可能吗?


[

  'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**',

  'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**'

]

提前感谢您的帮助


翻过高山走不出你
浏览 147回答 3
3回答

胡说叔叔

您还可以使用正则表达式来获取这些值。var arr = [&nbsp; &nbsp; "pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**",&nbsp; &nbsp; "pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**"];var results = [];for (var i=0; i < arr.length; i++) {&nbsp; &nbsp; var matches = arr[i].match(/\*\*(.+)\/(.+)\*\*/);&nbsp; &nbsp; if(matches && matches.length >= 3)&nbsp;&nbsp; &nbsp; results.push([matches[1], matches[2]]);}console.log(results);您可以在此处尝试代码 https://jsfiddle.net/p84eftL7/1/

慕运维8079593

首先,我没有完全回答你的问题。但据我所知,您希望这2个值位于数组中字符串的末尾。你可以试试这样的东西var a, b;for(s in YOUR_ARRAY){&nbsp; &nbsp; [...other, a, b] = YOUR_ARRAY[s].split("/");&nbsp; &nbsp; console.log(a, b);&nbsp; &nbsp; //Do whatever you want to do with a,b&nbsp;}让我解释一下我自己,首先你需要迭代你的数组,这就是为什么我们在这里有一个“for”循环。然后,对于由“YOUR_ARRAY[s]”给出的每个字符串,您将使用“/”作为分隔符拆分字符串。其余部分非常简单。供您参考,请浏览这些链接 https://www.w3schools.com/js/js_loop_for.asp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment更新:正如评论中提到的。如果你想有一个函数,那么function processValues(arr){&nbsp; &nbsp; var a, b;&nbsp; &nbsp; for(s in arr){&nbsp; &nbsp; &nbsp; &nbsp; [...other, a, b] = arr[s].split("/");&nbsp; &nbsp; &nbsp; &nbsp; console.log(a, b);&nbsp; &nbsp; &nbsp; &nbsp; //Do whatever you want to do with a,b&nbsp;&nbsp; &nbsp;}}processValues(YOUR_ARRAY);

慕标5832272

最后,我所做的是以下几点由于我必须引用回变量的名称,因此我使用以下内容来切片数组,以便可以使用索引号来引用需要检索的值:function() {&nbsp;var myStringArray = {{MY_ARRAY}};var arrayLength = myStringArray.length;var output = []for (var i = 0; i < arrayLength; i++) {var string = myStringArray[i].split("/",4)/*pull index 2 and 3 from string and convert to string*/output.push(string)&nbsp;}return output}之后,我必须循环上述信息中正在推送的新数组由于我只需要从该NEW_ARRAY_2拆分特定索引,因此我使用以下内容来执行此操作function() {var products = {{NEW_ARRAY_2}};var arr = []&nbsp;&nbsp;for (var i=0; i < products.length; i++) {var prod = products[i];var matches = prod[2];arr.push(matches);}var list = arr.join(', ')&nbsp;&nbsp;return list&nbsp;}2种产品的样品退货:“成人,青年”感谢您的支持
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript