首页 > 解决方案 > JavaScript 问题,它返回意外的值

问题描述

该程序的目标是返回存在于数组一个或另一个位置的值。问题是它返回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++;
        }

}

标签: javascriptundefined

解决方案


也许是一个更优雅的解决方案?

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()


推荐阅读