I have the following js code:
function splitter(somestr){
"use strict";
var bb0 = somestr.split(":");
return bb0;
}
var plist = [t_str, f_str, c_str, d_str, e_srt, o_str, k_str];
var aa0 = splitter(plist[0]);
var aa1 = splitter(plist[1]);
var aa2 = splitter(plist[2]);
var aa3 = splitter(plist[3]);
var aa4 = splitter(plist[4]);
var aa5 = splitter(plist[5]);
var aa6 = splitter(plist[6]);
I wanted to convert this into a for loop:
for (var k = 0; k < plist.length; k++) {
var a = plist[k];
var aa[k] = splitter(a);
return aa[k];}
What am i doing wrong, am I calling the splitter function within the loop incorrectly?
3 Answers 3
I'm guessing you want to store the values in aa, meaning you need to move it up in scope:
var aa = [];
for (var k = 0; k < plist.length; k++) {
var a = plist[k];
aa[k] = splitter(a);
}
// Do something with aa
answered Jan 22, 2014 at 6:36
Igor
34.3k14 gold badges83 silver badges116 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I am assuming you want to perform the splitter operation on each element of the plist array and store the results somewhere. Try:
var aa = plist.map(function(element){return splitter(element);})
answered Jan 22, 2014 at 6:40
tewathia
7,3383 gold badges26 silver badges28 bronze badges
Comments
Following doesn't make sense
function splitter(somestr){
**"use strict"; // This is not making sense**
var bb0 = somestr.split(":");
return bb0;
}
and also in the following a must be the an array to whom you are going to assigning values.
for (var k = 0; k < plist.length; k++) {
var a = plist[k];
var aa[k] = splitter(a);
return aa[k];}
3 Comments
Sterling Archer
Are you saying strict mode is not a good idea or do you not know what strict mode is?
Teemu
@user2951753 What??? Please read about Strict mode. Also why in world
a should be an array? a is passed to splitter(), and treated as a string there...user3213563
I've commented strict mode out.
lang-js
aa[0]is not the same asaa0var aa[k]. Instead of having variables with numeric indexes, use an array instead. So, before the loop:var aa = [];and in the loopaa[k] = ...;.