Thứ Ba, 5 tháng 10, 2021

Một số hàm tự tạo Javascript

 

1. Hàm định dạng lại cách hiển thị số, dựa trên hàm number_format() của PHP

number_format(giá trị số, số lượng chữ số sau dấu thập phân, dấu phân cách thập phân, dấu phân cách hàng nghìn)

Nguồn: StackOverflow

    number_format = function (number, decimals, dec_point, thousands_sep) {
number = number.toFixed(decimals);

var nstr = number.toString();
nstr += '';
x = nstr.split('.');
x1 = x[0];
x2 = x.length > 1 ? dec_point + x[1] : '';
var rgx = /(\d+)(\d{3})/;

while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

return x1 + x2;
}

2. Hàm kiểm tra isset và empty 

Nguồn: StackOverflowStackOverflow

    isset = function (variable) {
if (typeof variable !== "undefined" && variable !== null) {
return true;
}

return false;
}

empty = function (variable) {
if (Boolean(variable) === false || variable.length === 0) {
return true;
}

return false;
}




Không có nhận xét nào:

Đăng nhận xét