若语句,其中值等于一对多
If statement where value equals one on many?
所以我正在编写一个时区插件,我需要简化if语句,因为我想避免重复。我目前正在写它,以按州更改时间(是的,我知道有些州可能有多个时区。我稍后会完善它,可能按县。)
我们可以把所有可能的值都存储在一个变量中吗?下面,我有一个太平洋国家的数组,如何判断国家值是否等于其中之一?
jQuery
function GetClientTime() {
// current time
var dt = new Date();
// pacific time
var pacifictime = dt.getHours() - 2 + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
// mountain time
var mountaintime = dt.getHours() - 1 + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
// central time
var centraltime = dt.getHours() + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
// eastern time
var easterntime = dt.getHours() + 1 + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
// get am/pm
var hours = new Date().getHours();
var ampm = (hours >= 12) ? "PM" : "AM";
var pacificstates = [
"WA", "OR", "CA", "NV"
]
if ($('#state').val() == pacificstates) {
$('#currenttime').show().val(pacifictime + " " + ampm);
} else if ($('#state').val() == 'CO') {
$('#currenttime').show().val(mountaintime + " " + ampm);
} else if ($('#state').val() == 'TX' || $('#state').val() == 'LA') {
$('#currenttime').show().val(centraltime + " " + ampm);
} else if ($('#state').val() == 'NY' || $('#state').val() == 'NJ') {
$('#currenttime').show().val(easterntime + " " + ampm);
} else {
$('#currenttime').hide();
}
}
http://jsfiddle.net/q98sLy5c/1/
您可以在数组上使用indexOf()方法,如下所示:
if (pacificstates.indexOf($('#state').val()) !== -1)
如果该调用返回-1,则表示该元素不包含在该数组中。
工作示例请参见此处http://jsfiddle.net/q98sLy5c/2/
使用switch
语句:
switch
语句计算一个表达式,将该表达式的值与case
子句相匹配,并执行与该事例关联的语句。
var result = false;
swtich ( $('#state').val() ) {
/* If the value is "CO"... */
case 'CO':
result = pacifictime + " " + ampm;
break;
/* If the value is "TX" or "LA"... */
case 'TX':
case 'LA':
result = entraltime + " " + ampm;
break;
default:
break;
}
/* If the result was set, display the result. */
if (result)
$('#currenttime').show().val( result );
/* Otherwise, hide it. */
else
$('#currenttime').hide();
如果您试图从一个状态转到另一个时区,使用对象可能是最节省时间的方法。
var stateToTimeZone = {};
stateToTimeZone['TX'] = entraltime + " " + ampm;
stateToTimeZone['LA'] = entraltime + " " + ampm;
stateToTimeZone['CO'] = pacifictime + " " + ampm;
. . .
var result = stateToTimeZone[$('#state').val()];
if (result)
$('#currenttime').show().val( result );
/* Otherwise, hide it. */
else
$('#currenttime').hide();
基本上,您是在用更快的时间换取更多的内存使用。但我认为这就是你在这种情况下想要做的。它也可以很容易地扩展到县,只需使用"WA_King"这样的键,因为同一个县名可能出现在不同的州。
相关文章:
- 如何在Parse中创建一对多关系
- Ember数据一对多关系不起作用
- 解析-在数组一对多关系中获取父项及其子项
- 集合作为 EmberJS 中的属性?(一对多关系)
- JayData一对多预测
- 我将如何解决余烬数据中的这种一对多态关系
- 与 RequireJS 和 Backbone 的一对多和一对一关系
- 从SQL一对多到解析NoSQL
- 续集JS:包括一对多关系船
- 帆.js:模型本身的一对多关系
- 余烬类型未定义且加载路线出错,具有一对多关联
- 流星:如何使关系一对多
- 对于具有一对多关系的主干模型,存储“;许多“;数组中的模型,而不是Collection
- Sails.js-一对多映射
- 一对多关系的简单解析查询
- knex js-一对多关系
- MongoDB和Meteor.js-一对多引用
- 主干.js和嵌入式一对多关联
- Parse(js)和嵌套查询中的一对多关系
- 若语句,其中值等于一对多