risefire risefire - 1 year ago 165
Javascript Question

Changing forEach loop to for-loop in javascript

I currently have a forEach loop like this.

var videoUrls ={};
.forEach(function(item) {
var obj = { };
.forEach(function(param) {
param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);

videoUrls[obj.quality] = obj;});

Since IE is not supporting forEach loop, I tried to convert this to for loop.

var videoUrls ={};
var typea= ytplayer.config.args.url_encoded_fmt_stream_map.split(',');
for (var item=0; item<typea.length; item++){
var obj= {};
var typeb= typea[item].split('&');
for (var param=0; param<typeb.length; param++){

typeb[param]= typeb[param].split('=');
obj[typeb[0]] = decodeURIComponent(typeb[1]);

videoUrls[obj.quality]= obj;

But when I run the script the results were different. What did i do wrong?

Thanks in advance.

Answer Source

it should be:

typeb[param]= typeb[param].split('=');
obj[typeb[param][0]] = decodeURIComponent(typeb[param][1]);

Because the other loop is:

param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);


obj[item.split("&")[0]] = decodeURIComponent(item.split("&")[1])

If it's still not clear, here is a simpler explanation:

typeb === item.split("&");
typeb[param] === param;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download