1

The objective of the program is to return the value that exists in one position of an array or another. The problem is that it returns undefined.

var ONE = ["a1", "b1", "c1", "d1"];

var TWO = ["a2", "b2", "c2", "d2"];

// ONCLICK 
function main() {
  var p = prompt("Choose the ONE variable array or the TWO variable array");
  var l = parseInt(prompt("Choose de position of the value of that array"));        
  console.log(second(l));
  second(p,l);                                          
}

function second(p,l) {
    if (p == "ONE")
        i = 0;
        while (i < 11){
            if (ONE[i] == l){
                return l;
            }
            i++;
        }

    if (p == "TWO")
        i = 0;
        while (i < 11){
            if (TWO[i] == l){
                return l;
            }
            i++;
        }

}

2
  • 3
    you're only passing one argument into second() the first time you call it. So p will be defined but l won't be. Commented Mar 26, 2020 at 13:19
  • 1
    well second is called but you do nothing with the returned value..... and your console does not match the line under it,..... Commented Mar 26, 2020 at 13:22

3 Answers 3

1

It's not clear if the position is an index of an array. If it's i'd be something like that

var ONE = ["a1", "b1", "c1", "d1"];
var TWO = ["a2", "b2", "c2", "d2"];

function second(p,l) {
    if (p === "ONE") {
        return ONE[l];
    }

    if (p === "TWO") {
        return TWO[l];
    }
}

second("ONE", 0); // output "a1"
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps a more elegant solution?

const arrays = {
  ONE : ["a1", "b1", "c1", "d1"],
  TWO : ["a2", "b2", "c2", "d2"]
}

// ONCLICK 
function main() {
  var p = prompt("Choose the ONE variable array or the TWO variable array");
  var l = parseInt(prompt("Choose de position of the value of that array"));
  console.log(second(p,l));
  second(p, l);
}

const second = (p, l) => arrays[p][l];

main()

Comments

0
console.log(second(l));

With this code you are calling the function with the first parameter so "p" and no "l" ("l" is undefinded) so when it evaluates its result it's going to return undefinded.

Comments

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.