jQuery分割一个子数组,并使用each/map返回一个新数组 [英] jquery malipulate a subarray, and return a new array using each/map
问题描述
我的字符串形式为
ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4
(依此类推,直到第25条).
ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4
(and so on, upto item 25).
我要做的是,当该字符串被_
分割时,用户将传递一个索引,(例如2)在该索引处抓取该项目,例如.如果index为2,我将得到子字符串ItemName3:Rate3:Tax3
.用户将传递的另一件事是3个参数,分别表示newItem
,newRate
和newTax
,然后我必须用这些新值和替换在该特定索引处找到的这些旧项目.新的字符串.也许一个例子可以清楚地说明
What I have to do is, user will pass a index, (say 2) grab the item at that index, when this string is split by _
, for eg. if index is 2, I would get the substring ItemName3:Rate3:Tax3
. another thing the user will pass is 3 args, indicating newItem
, newRate
, and newTax
, then I have to replace these old items found at that particular index with these new values and return the new string. Perhaps an example would make it clear
var itemList=ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4
用户传递的参数2, Denim Jeans, 399.00, 14.34
.
这必须替换原始的itemList
并返回
user passed arguments, 2, Denim Jeans, 399.00, 14.34
.
This must replace the original itemList
and return
ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_Denim Jeans:399.00:14.34_ItemName4:Rate4:Tax4
(希望我说清楚了).
我知道最简单的方法是先将itemList
除以_
,然后在给定的索引处,除以:
,然后替换那些项,然后使用for循环创建一个新字符串,然后返回该新字符串.但这似乎需要大量工作.尽管可能在for
内,但没有简单的方法可以通过使用.each()
和/或.map()
来实现这一点,我不介意!
(Hope I made myself clear).
I know the simplest way would be first split the itemList
by _
and then at given index, split by :
and then replace those items, then using a for loop make a new string and then return that new string. But it seems like a lot of work. Isn't there a simple way that this could be achieved by using .each()
and/or .map()
, though may be inside a for
, I won't mind that!
推荐答案
您的意思是这样的吗?
var items = str.split('_').map(function(v){ return v.split(':') });
这将生成一个数组:
[
["ItemName1","Rate1","Tax1"],
["ItemName2","Rate2","Tax2"],
["ItemName3","Rate3","Tax3"],
["ItemName4","Rate4","Tax4"]
]
演示: http://jsfiddle.net/elclanrs/7uVDM/
这篇关于jQuery分割一个子数组,并使用each/map返回一个新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!