数组等于两个不同的值,并动态更改变量
Array equal two different values and change a variable dynamically
我希望用户输入一个ID号。当用户单击按钮时,代码将查找一个包含所有 ID 号列表的数组,以检查它是否存在。然后,它将检查该ID号的价格。根据价格和查找的ID号,我希望它动态更改一个名为"成本"的变量。例如,用户在数字"5555"中键入代码会查找 ID 5555 是否存在,如果存在,它会检查该 id 的价格。基于这个价格,我希望它改变一个名为成本的变量。同样,如果我查找 id "1234"。它会查找id,如果存在,得到价格,然后更改称为成本的变量。
我什至不知道从哪里开始。我正在考虑使用数组来映射 ID 号和价格,但我不知道这是否有效。我希望一个数字基本上等于另一个数字,然后根据第二个数字更改变量,我想不出该怎么做。
id[0] = new Array(2)
id[1] = "5555";
id[2] = "6789";
price = new Array(2)
price[0] = 45;
price[1] = 18;
您可以将对象用作类似字典的对象。
// Default val for cost
var cost = -1;
// Create your dictionary (key/value pairs)
// "key": value (e.g. The key "5555" maps to the value '45')
var list = {
"5555": 45,
"6789": 18
};
// jQuery click event wiring (not relevant to the question)
$("#yourButton").click(function() {
// Get the value of the input field with the id 'yourInput' (this is done with jQuery)
var input = $("#yourInput").val();
// If the list has a key that matches what the user typed,
// set `cost` to its value, otherwise, set it to negative one.
// This is shorthand syntax. See below for its equivalent
cost = list[input] || -1;
// Above is equivalent to
/*
if (list[input])
cost = list[input];
else
cost = -1;
*/
// Log the value of cost to the console
console.log(cost);
});
相关文章:
- Symfony 2根据选定的值动态改变形式
- 动态改变ng重复
- 动态改变宽度时闪烁
- 动态改变Amcharts中的valueAxis
- Angular2动态改变CSS属性
- 基于查看区域,使用javascript动态改变html对象中嵌入flash文件的大小
- 在Laravel 5.3中动态改变图像
- 嵌入ng-src不动态改变
- 动态改变按钮的文本与javascript
- 在材质设计和angularjs中不动态改变状态的复选框
- js -如何动态改变对象的不透明度
- 如何动态改变jquery日期选择器样式
- 如何在元素悬停时动态改变文本
- 如何动态改变帧的SRC
- 使用指令式Angular JS动态改变文本的颜色
- 如何动态改变html5视频源
- Jquery内容滑块插件,可以动态改变幻灯片的顺序
- 动态改变颜色与JQuery
- 类名从Angular.js中的JSON对象动态改变
- 动态改变使用int值的变化