JS 循环问题。

skyflyzy 2018-05-30 03:00:15

let colArry = [];
let ts_cost = '321##深圳市代理有限公司##{"RMB":"175.00"}||321##深圳市代理有限公司##{"RMB":"175.00"}||321##深圳市代理有限公司##{"RMB":"175.00"}||321##深圳市代理有限公司##{"RMB":"175.00"}';

if(ts_cost && ts_cost !== '') {
const ts_cost_arry = ts_cost.split('||');
let json = {"belong_custom":"", "belong_corp":"", "collection":""};
for(let i=0;i<ts_cost_arry.length;i++){
const [a,b,c] = ts_cost_arry[i].split('##'); //{"RMB":"1111.72","HK":"62.03"}

if(a) {
json.belong_custom = a;
json.belong_corp = b;
json.collection = c;

let find = -1;
console.log(colArry,i);
for (let k = 0,max = colArry.length; k < max; k++) {
if (colArry[k].belong_custom === a && colArry[k].belong_corp === b) {
let oldCol = JSON.parse(colArry[k].collection);
let newCol = JSON.parse(c);

for(let key in newCol){
if(parseFloat(newCol[key])!==0 && newCol.hasOwnProperty(key)){
if(oldCol[key]) {
oldCol[key] = parseFloat(oldCol[key]) + parseFloat(newCol[key]);
}else {
oldCol[key] = newCol[key];
}
}
}

json.collection = JSON.stringify(oldCol);
find = k;
break;
}
}

if(find>=0) colArry.splice(find,1,json);
else colArry.push(json);
colArry[0].title = i;
console.log(colArry,'end');
}
}
}


其实就是判断字符串用##分隔的第一个数值和第二个数值相同的,就合并第三个数值中相同币制的金额。
[] 0
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":"175.00"}',
title: 0 } ] 'end'
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":"175.00"}',
title: 0 } ] 1
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":350}',
title: 1 } ] 'end'
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":"175.00"}',
title: 1 } ] 2
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":350}',
title: 2 } ] 'end'
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":"175.00"}',
title: 2 } ] 3
[ { belong_custom: '321',
belong_corp: '深圳市代理有限公司',
collection: '{"RMB":350}',
title: 3 } ] 'end'

上面是调试结果, 可以看到i为1时,金额已经累加到350了, 但在i为2时, 取值时金额又变成175了, 百思不得其解, 请指点!

200分奉上。
...全文
344 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
skyflyzy 2018-05-30
  • 打赏
  • 举报
回复
感谢, 终于搞定了。
天际的海浪 2018-05-30
  • 打赏
  • 举报
回复
for(let i=0;i<ts_cost_arry.length;i++){ let json = {"belong_custom":"", "belong_corp":"", "collection":""}; 这两行位置交换下

87,907

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧