javascript - 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++;
}
}
解决方案
也许是一个更优雅的解决方案?
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()
推荐阅读
- bluetooth - 蓝牙准备好 systemd 后无法启动任务
- angular - 在 Spring-mvc 项目文件夹中放置 angular8 构建文件的位置(+ 用于 NG 的正确 AppConfig.java?)
- python - folium MarkerCluster 如何在 python 中为颜色编写 icon_create_function
- reactjs - 如何使 webpack / react 和电子在安全的上下文中工作?
- android - 当原始 URL 需要标头时,从缓存中播放 ExoPlayer 失败
- azure - 如何在 azure key Vault 中存储多个值/对象
- javascript - SassError:此文件已被加载。@import '~src/css/quasar.variables.scss', 'quasar/src/css/variables.sass'; src\css\quasar.variables.scss
- microsoft-teams - 优化 github 操作中基于条件的 MSTeam 通知
- python - 在 github 上下载文件名不一致的最新更新
- python - 如果在另一个循环中满足条件,则中断循环