我正在尝试从switch语句(<ol class="lower-alpha" start="2">
<li>Explain...</li>
<li>Describe...</li>
<li value="5">Calculate...</li>
</ol>
,value
,breakMonValue
)中添加多个值,以便我可以finishMonValue
将这些值添加在一起,并希望知道这是否可能吗?
未定义startMonTimeStr变量
console.log
它们的布局如下:
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var timeStringToValue = function timeStringToValue(timeStr) {
var _timeStr$match = timeStr.match(/(\d+):(\d+) ([ap]m)/),
_timeStr$match2 = _slicedToArray(_timeStr$match, 4),
hours = _timeStr$match2[1],
minutes = _timeStr$match2[2],
ampm = _timeStr$match2[3];
var ampmHourModifier = ampm === 'pm' ? 12 : 0;
return Number(hours) + ampmHourModifier + minutes / 60;
};
var startMonTimeStr = $('.start-time-monday option:selected').text();
var startMonValue = timeStringToValue(startMonTimeStr);
console.log(timeStringToValue(StartMonValue));
console.log(timeStringToValue('3:30 pm'));
答案 0 :(得分:1)
使用数学将时间字符串解析为数字可能会更优雅,例如:
const timeStringToValue = (timeStr) => {
const [, hours, minutes, ampm] = timeStr.match(/(\d+):(\d+) ([ap]m)/);
const ampmHourModifier = ampm === 'pm' ? 12 : 0;
return Number(hours) + ampmHourModifier + (minutes / 60)
};
console.log(timeStringToValue('10:00 am'));
console.log(timeStringToValue('3:30 pm'));
然后您可以调用它:
const startMonTimeStr = $('.start-time-monday option:selected').text();
const startMonValue = timeStringToValue(startMonTimeStr);
和
const finishMonTimeStr = $('.finish-time-monday option:selected').text();
const finishMonValue = timeStringToValue(finishMonTimeStr);
switch
在大多数情况下都是不必要的冗长和丑陋,这也不例外。
如果您想将所有总数相加,请进行更改以计算每个小计,例如:
const getBreakTotal = () => {
const minutes = $('.meal-break-monday option:selected').text().match(/^\d+/)[0];
return minutes / 60;
};
const getAllTotals = () => {
const startTotal = timeStringToValue($('.start-time-monday option:selected').text());
const breakTotal = getBreakTotal();
const finishTotal = timeStringToValue($('.finish-time-monday option:selected').text());
console.log(startTotal + breakTotal + finishTotal);
};
$('.start-time-monday, .meal-break-monday, .finish-time-monday').on('change', getAllTotals);