【发布时间】:2014-11-20 20:44:11
【问题描述】:
我试图弄清楚如何创建一个函数来添加用户选择的元素的值,并能够通过提示和 console.log 显示结果。另外,我想知道是否有一种方法可以做到这一点,我不需要指定选择的元素,以便函数在代码中找到选择了哪些元素并执行添加功能。因为很明显,如果选项列表更长,我不想为每个可能的选择组合创建一个新函数。附带说明一下,我想同样的问题也适用于 if 语句,switch 语句是解决该实例中“DRY”代码需求的最有效方法吗?
我的 javascript 代码:请假设用户只选择嵌套数组的第一个元素。此外,“一”这个词值 8 美元。
var selection = new Array (3);
selection[0] = new Array ('$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8');
selection[1] = new Array ('phone1', 'phone2', 'phone3');
selection[2] = new Array ('one', 'two', 'three');
function pickPhone () {
var yourPhone = prompt("pick phone: phone1: $1, phone2: $2, phone3: $3");
if (yourPhone == selection[1][0]) {
console.log(selection[1][0] + " will cost: " + selection[0][0]);
alert(selection[1][0] + " will cost: " + selection[0][0]);
pickTerm ();
} if (yourPhone == "phone2") {
alert(selection[1][1] + " will cost: " + selection[0][1]);
} if (yourPhone == "phone3") {
alert(selection[1][2] + " will cost: " + selection[0][2]);
}
}
function pickTerm () {
var yourTerm = prompt("pick term: one, two or three?");
if (yourTerm == selection[2][0]) {
alert("Your total so far is: ??");
}
}
pickPhone ();
非常感谢任何帮助,谢谢。
【问题讨论】:
-
你最好使用类似的对象:
var data = {costs:[1,2,3], phones:[1,2,3], other:[1,2,3]}。
标签: javascript arrays function variables operators