1

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?

4
  • Without knowing what is inside the array, the expected output vs what you get, we can't answer this. Commented Jan 22, 2014 at 6:36
  • aa[0] is not the same as aa0 Commented Jan 22, 2014 at 6:36
  • You are calling the function correctly, but you cannot have a variables declaration like var aa[k]. Instead of having variables with numeric indexes, use an array instead. So, before the loop: var aa = []; and in the loop aa[k] = ...;. Commented Jan 22, 2014 at 6:46
  • each element n the array plist is in the form 8:20 i.e. a time. The splitter function splits the desired element in p-list into a 2-wide array. Commented Jan 22, 2014 at 6:46

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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);})

Comments

-1

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

Are you saying strict mode is not a good idea or do you not know what strict mode is?
@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...
I've commented strict mode out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.