This is not a problem $.each, var a = {};- it is an object, and $.each(a, function (secs, str) {})it turns out badly, because jQuery each function only accepts an array.
need to convert objectto array, then use the function $.each.
Added new code to the function body to create objectup toarray
var temp = [];
var finalArr = [];
for (val in a) {
temp.push(val);
}
temp = temp.sort(function (a, b) {
return a - b
});
for (var i = 0; i < temp.length; i++) {
finalArr.push(a[temp[i]] + "|" + temp[i]);
}
and also changed the way to access the data and index of the newly created array
function time_remaining(expire_time) {
var now = new Date().getTime() / 1000,
time_left = expire_time - now,
time_left_str = '0 seconds';
if (time_left < 1) {
return time_left_str;
}
var a = {};
a[12 * 30 * 24 * 60 * 60] = 'year',
a[30 * 24 * 60 * 60] = 'month',
a[24 * 60 * 60] = 'day',
a[60 * 60] = 'hour',
a[60] = 'minute',
a[1] = 'second';
var temp = [];
var finalArr = [];
for (val in a) {
temp.push(val);
}
temp = temp.sort(function (a, b) {
return a - b
});
for (var i = 0; i < temp.length; i++) {
finalArr.push(a[temp[i]] + "|" + temp[i]);
}
$.each(finalArr, function (secs, str) {
var time = time_left / parseInt(str.split("|")[1], 10);
if (time >= 1) {
var randomNum = Math.round(time);
time_left_str = randomNum + ' ' + str.split("|")[0] + ((randomNum > 1) ? 's' : '');
return true;
}
});
return time_left_str;
}
source
share