Abaixo estão algumas verificações e funções do JS que eu costumo usar. Algumas verificações que escrevi diretamente nas propriedades do objeto e podem ser chamadas diretamente através do objeto.
A cópia do código é a seguinte:
// Operação de divisão de ponto flutuante
função fdiv (a, b, n) {
if (n == indefinido) {n = 2; }
var t1 = 0, t2 = 0, r1, r2;
tente {t1 = a.toString (). Split (".") [1] .Length} Catch (e) {}
tente {t2 = b.toString (). Split (".") [1] .Length} Catch (e) {}
com (matemática) {
r1 = número (a.toString (). substituir (".", ""));
r2 = número (B.ToString (). Substituir (".", "");
Retorno ((R1 / R2) * Pow (10, T2 - T1)). tofixado (n);
}
}
A cópia do código é a seguinte:
// Operação de multiplicação de ponto flutuante
função fmul (a, b, n) {
if (n == indefinido) {n = 2; }
var m = 0, s1 = a.toString (), s2 = b.toString ();
tente {m += s1.split (".") [1] .Length} Catch (e) {}
tente {m += s2.split (".") [1] .length} catch (e) {}
return (número (s1.Replace (".", "")) * número (s2.replace (".", "")) / math.pow (10, m)). tofixed (n);
}
A cópia do código é a seguinte:
// Operação de adição de número de ponto flutuante
função faadd (a, b, n) {
if (n == indefinido) {n = 2; }
var r1, r2, m;
tente {r1 = a.toString (). split (".") [1] .Length} Catch (e) {r1 = 0}
tente {r2 = b.toString (). split (".") [1] .Length} Catch (e) {r2 = 0}
M = Math.pow (10, Math.max (R1, R2))
return ((a * m + b * m) / m) .tofixado (n);
}
A cópia do código é a seguinte:
// Operação de subtração do número do ponto flutuante
função fsub (a, b, n) {
if (n == indefinido) {n = 2; }
var r1, r2, m;
tente {r1 = a.toString (). split (".") [1] .Length} Catch (e) {r1 = 0}
tente {r2 = b.toString (). split (".") [1] .Length} Catch (e) {r2 = 0}
M = Math.pow (10, Math.Max (R1, R2));
// Comprimento de precisão de controle dinâmico
// n = (r1> = r2)? r1: r2;
return ((a * m - b * m) / m) .tofixado (n);
}
Número.prototype.add = function (arg) {
retornar Fadd (isto, arg);
}
Número.prototype.subs = function (arg) {
devolver fsub (este, arg);
}
Número.prototype.mul = function (arg) {
retornar fmul (este, arg);
}
Número.prototype.div = function (arg) {
retornar fdiv (este, arg);
}
A cópia do código é a seguinte:
/// formato o número de dígitos, o número de dígitos insuficientes é 0 por padrão. Se o parâmetro 2 for especificado e o valor do parâmetro 2 for 1, o lado direito será 0 por 0 se o parâmetro 2 for especificado.
Número.prototype.formatlen = function (len, direto) {
var d = parseint (direto);
if (isnan (d)) {d = 0; }
var num = this.toString ();
if (num.length <len) {
for (var i = num.length; i <len; i ++) {
if (d == 0) {
num = "0" + num;
}
outro {
num += "0";
}
}
}
retornar num;
}
A cópia do código é a seguinte:
// formate os lugares decimais, você pode especificar o número de lugares decimais, seja ou não e não e outros parâmetros como
Número.prototype.formatRadix = function (len, isround) {
var num = this.toString ();
var numarr = num.split ('.');
var rad = 0;
var numpart = parseint (numarr [0]);
if (numarr.Length> = 2) {
if (numarr [1] .Length <len) {
rad = parseint (numarr [1]). formatlen (len, 1);
}
outro {
if (numarr [1] .Length == len) {
rad = numarr [1];
}
outro {
rad = numarr [1] .substr (0, len);
if (isround) {
var d = parseint (numarr [1] .substr (len, 1));
if (d> = 5) {rad += 1; if (rad.ToString (). Comprimento> len) {Numpart += 1; rad = rad.toString (). substr (1, len); }}
}
}
}
}
outro {
rad = rad.formatlen (len);
}
Retornar Numpart + "." + rad;
}
A cópia do código é a seguinte:
// Detecte se o mesmo elemento na divisão da string é um separador de string. Se um separador for especificado, é determinado se há duplicação do delimitador de string. Se não for especificado, é determinado se há duplicação de uma única string.
// retorna true se houver uma duplicata
String.prototype.comPareElement = Função (s) {
var str = this.toString ();
if (s == indefinido) {
for (var i = 0; i <str.Length; i ++) {
for (j = i+1; j <str.Length; j ++) {
if (str.substr (i, 1) == str.substr (j, 1)) {
retornar true;
}
}
}
}
outro {
var starr = str.split (s);
for (var i = 0; i <Starr.Length; i ++) {
for (var j = i+1; j <Salarr.Length; j ++) {
if (Starr [i] == Salarr [j]) {
retornar true;
}
}
}
}
retornar falso;
}
String.prototype.replaceall = function (str, tostr) {
astr = this;
while (ostr.indexof (str)> -1) {
astr = ostr.Replace (str, tostr);
}
retornar ostr;
}
Array.prototype.compareElement = function () {
var starr = this;
for (var i = 0; i <Starr.Length; i ++) {
for (var j = i+1; j <Salarr.Length; j ++) {
if (Starr [i] == Salarr [j]) {
retornar true;
}
}
}
retornar falso;
}
A cópia do código é a seguinte:
// A sequência é convertida no número de grupos. Se o delimitador S não for especificado, o delimitador será delimitado por padrão. Se o delimitador estiver vazio, cada caractere será usado como um elemento de matriz.
String.prototype.toArray = função (s) {
if (s == indefinido) {s = ","; }
var starr = [];
starr = this.split (s);
retornar Salarr;
}
A cópia do código é a seguinte:
// converte uma matriz em uma string, todos os elementos estão conectados usando o delimitador especificado, e o padrão é,
Array.prototype.toidList = função (s) {
if (s == indefinido) {s = ","; }
var lista = "";
for (var i = 0; i <this.length; i ++) {
lista + = (list == ""? Isso [i]: s + "" + this [i]);
}
lista de retorno;
}
A cópia do código é a seguinte:
// Obtenha o índice de localização do elemento especificado, o elemento não existe e retorna -1
Array.prototype.getIndex = função (s) {
var index = -1;
for (var i = 0; i <this.length; i ++) {
if ((s + "") == this [i]) {
índice = i;
}
}
Índice de retorno;
}
A cópia do código é a seguinte:
// Remova o elemento especificado da matriz
Array.prototype.remove = função (s) {
var lista = "";
for (var i = 0; i <this.length; i ++) {
if (s! = this [i]) {
lista + = (list == ""? Isso [i]: "," + this [i]);
}
}
list de retorno.toArray ();
}
A cópia do código é a seguinte:
/// Classifique a matriz numericamente as ASC especifica se deve classificar as ASC. Pode ser verdadeiro ou falso, não especificado como ordem ascendente.
Array.prototype.sortByNumber = function (ASC) {
if (ASC == indefinido) {ASC = true; }
if (ASC) {
retornar este.sort (sortNumberasc);
}
outro {
retornar este.sort (sortNumberDesc);
}
}
Array.prototype.inArray = function (e) {
var isin = false;
for (var i = 0; i <this.length; i ++) {
if (este [i] == (e + "")) {
Isin = true;
}
}
retornar isin;
}
String.prototype.trim = função (s) {return Trim (this, s); }
String.prototype.ltrim = função (s) {return ltrim (this, s); }
String.prototype.rtrim = função (s) {return rtrim (this, s); }
// Sortbynumer para classificar os números em ordem decrescente em matriz
função sortNumberdesc (a, b) {
retornar b - a;
}
// Sortbynumer para classificar os números em ordem crescente em matrizes com a Array.sortbynumer
função sortNumberasc (a, b) {
retornar a - b;
}
// Esta é uma função independente
função ltrim (str, s) {
if (s == indefinido) {s = ""; }
if (str == s && s! = "") {return s; }
var i;
para (i = 0; i <str.Length; i ++) {
if (str.charat (i)! = s && str.charat (i)! = s) quebra;
}
str = str.substring (i, str.length);
retornar str;
}
função rtrim (str, s) {
var i;
if (str == s && s! = "") {return s; }
if (s == indefinido) {s = ""; }
for (i = str.Length-1; i> = 0; i--) {
if (str.charat (i)! = s && str.charat (i)! = s) quebra;
}
str = str.substring (0, i + 1);
retornar str;
}
Função Trim (str, s) {
retornar lTRIM (rtrim (str, s), s);
}
A cópia do código é a seguinte:
/// Detecção se a string é composta por chinês, inglês, números e sublinhados
função chknickname (str) {
var padrão =/^[/w/u4e00-/u9fa5]+$/gi;
if (padrão.test (str)) {
retornar true;
}
retornar falso;
}
A cópia do código é a seguinte:
// O comprimento do juiz (o comprimento não é limitado a 0)
String.prototype.islen = function () {
var isrightFormat = false;
var minnum = argumentos [0]? argumentos [0]: 0;
var maxnum = argumentos [1]? argumentos [1]: 0;
isrightformat = (minnum == 0 && maxnum == 0? true: (calcular_byte (this)> = minnum && calculou_byte (this) <= maxnum? true: false));
retornar isrightformat;
}
A cópia do código é a seguinte:
// Verifique se a string é uma letra +número +_ +-
String.prototype.isstr = function () {
var myreg =/^[0-9a-za-z/-/_]+$/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o nome de usuário
String.prototype.isusername = function () {
var myreg =/^[0-9a-za-z/-/_] {3,50} $/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique a senha
String.prototype.ispassword = function () {
var myreg =/^[0-9a-za-z` ~!@#$%^&*() -_+=/{/}/[/]/;/:/"/'/? ////] {6,} $/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique se é uma carta
String.prototype.isen = function () {
var myreg = /^[a-za-z]+$ /;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique se são caracteres chineses
String.prototype.iscn = function () {
var myreg =/^[/u0391-/uffe5]+$/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o e-mail
String.prototype.isemail = function () {
var myreg = /(:/w-/. ]+)@(//ativamente
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o msn
String.prototype.ismsn = function () {
var myreg = /(:/w-/. ]+)@(//ativamente
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o número QQ
String.prototype.isqq = function () {
var myreg =/^[1-9]/d {4,10} $/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o URL
String.prototype.ishttpurl = function () {
var myreg = /^http:////.
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o nome do domínio
String.prototype.isDomainName = function () {
var myreg = /^.0-9a-za-z ](.0-9a-za-z/- ]+/.) {1,3}
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o endereço IPv4
String.prototype.isipv4 = function () {
var myreg = /^(2[0-5] {2}|1?
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o endereço da imagem (as imagens geradas dinamicamente por CGI não são suportadas)
String.prototype.isimgurl = function () {
var myreg = /^/.(jpeg|jpg|gif|bmp|png|pcx|tiff|tga|lwf)$/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o número do celular
String.prototype.iscellphone = function () {
var myreg =/^((/(/d {3}/)) | (/d {3}/-))? 1 [3,5]/d {9} $/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o telefone fixo
String.prototype.isphone = function () {
var myreg =/^[+] {0,1} (/d) {1,3} []? ([-]? (((/d) | []) {1,12})+$/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o código postal
String.prototype.iszipcode = function () {
var myreg = /[0-9] {6} /;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o número de identificação
String.prototype.isidcard = function () {
var myreg =/(^([/d] {15} | [/d] {18} | [/d] {17} [xx] {1}) $)/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verificar a data do formato yy-mm-dd
String.prototype.isdateFormat = function () {
var myreg = /^[0-9] {4}-[0-9] {1,2}-[0-9] {1,2} $ /;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verificar o formato de tempo HH: MM: SS
String.prototype.israngETime = function () {
var myreg =/^(/d {2}): (/d {2}): (/d {2}) $/;
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Verifique o formato da quantidade
String.prototype.ismoney = function () {
var myreg = /^.0-9] {1,8a }.] {0,1}.
if (myreg.test (this)) retorna true;
retornar falso;
}
A cópia do código é a seguinte:
// Palavras Verifique o formato numérico e julgue o ambiente do número (min: valor mínimo; máximo: valor máximo.)
String.prototype.isint = function () {
var isrightFormat = false;
var minnum = argumentos [0]? argumentos [0]: 0;
var maxnum = argumentos [1]? argumentos [1]: 0;
var myreg =/^[-/+]?/d+$/;
if (myreg.test (this)) {
isrightformat = (minnum == 0 && maxnum == 0? true: (this> minnum && this <maxnum? true: false));
}
retornar isrightformat;
}
A cópia do código é a seguinte:
// Verifique as palavras -chave de pesquisa
String.prototype.issearch = function () {
var myreg = /^//|/"/ '.
if (myreg.test (this)) retorna false;
retornar true;
}
A cópia do código é a seguinte:
// JS calcula com precisão o comprimento da string
função calcular_byte (stargetstr) {
var stmpstr, stmpchar;
var noriginlen = 0;
var nstrLength = 0;
stmpstr = new String (StargetStr);
noriginlen = stmpstr.length;
for (var i = 0; i <noriginlen; i ++) {
stmpchar = stmpstr.charat (i);
if (escape (stmpchar) .Length> 4) {
NstrLength += 2;
} else if (stmpchar! = '/r') {
NStrLength ++;
}
}
Retornar NstrLength;
}
A cópia do código é a seguinte:
// valor de cor;
String.prototype.iscolor = function () {
var s = argumentos [0]? argumentos [0]: "";
s = s.trim ();
if (s.length! = 7) retorna false;
retornar S.Search (//#[a-fA-f0-9] {6}/)! = -1;
}
A cópia do código é a seguinte:
// JS Data Formating
Date.prototype.format = function (formato) {
var o = {
"M +": this.getmonth () + 1, // mês
"D+": this.getdate (), // dia
"H+": this.gethours (), // hora
"M+": this.getminutes (), // minuto
"S+": this.getSeconds (), // Second
"q +": math.floor ((this.getmonth () + 3) /3), // trimestre
"S": this.getMillisEconds () // milissegundos
}
if (/(y+)/.test(format)) {
format = format.Replace (regexp. $ 1, (this.getlyear () + "") .substr (4 - regexp. $ 1.Length));
}
para (var k em o) {
if (novo regexp ("(" + k + ")"). test (formato)) {
formato = format.Replace (regexp. $ 1, regexp. $ 1.Length == 1? O [k]: ("00" + o [k]). substr (("" + o [k]). comprimento));
}
}
Formato de retorno;
}
função haschinese (valor) {
if (/^/u4e00-/u9fa5 ]+$/.test(value)) {
retornar true;
}
retornar falso;
}
função TODATE (DATEST) {
var dstr = DATEST.ToString ();
DATEST = DSTR.Replaceall ("-", "/");
retornar nova data (DATE.PARSE (DATEST);
}
A cópia do código é a seguinte:
// é a lista de identificação?
String.prototype.isidlist = função (s) {
if (s == indefinido) {
s = ",";
}
var arr = this.split (s);
for (var i = 0; i <arn.length; i ++) {
if (isnan (parseint (arr [i]))) {return false; }
}
retornar true;
}
A cópia do código é a seguinte:
// Pegue o objeto acionado pelo evento
função getEventTarget (e) {
e = e || Window.Event;
Retornar E.Target || E.Srcelement;
}
O código é simples, mas as funções são muito práticas. Por favor, consulte, se precisar.