JavaScript JavaScript 1.5 ECMAScript ECMA-262, 3 rd edition Datové typy / literály null undefined logické hodnoty true, false čísla 42, 0xFF, 3.1415, -.12e-4, NaN, -Infinity řetězce "hello", 'world', "one line\nanother line" regulární výrazy /ab+c/, /\w+\s/g Datové typy / literály pole ["coffee", "tea", "cocoa"], ["cat",, "dog"] objekty {key1: "value1", key2: ["array", "of", "values"], key3: {a: "object", b: "value"}} funkce function(x) { return x * x } Konverze na boolean false: undefined, null, false, 0, NaN, "" true: zbytek (tedy i libovolný objekt, včetně new Boolean(false))
Operátory přiřazení = += -= *= /= %= <<= >>= >>>= &= ^= = porovnání ==!= ===!== > >= < <= aritmetika + - * / % ++ -- & ^ ~ << >> >>> logické &&! ostatní podmínkový operátor (?:), čárka (,), delete, in, instanceof, new, this, typeof, void Syntax (cykly) for(i=0;i<10;i+){ statements o{statements while(i<10); hile(i<10){ tatements }d } ws Proměnné začínají písmenem, podtržítkem nebo dolarem další znaky mohou být též číslice x = 42 var x = 42 const y = 43 Syntax (větvení) if(i>0){ s tatements1 }e lse{statements2 }s witch(i){ c ase0:statements1 b reak; c ase1:statements2 c ase2:statements3 b reak; d efault:statements4 }
Syntax label: statement break [label], continue [label] // single-line comment /* multiple-line comment */ Syntax (výjimky) try{/functioncouldthrowthrexceptions getcustinfo("le",1234,"le@netscapėcom") }catch(eife="invalidnameexception"){ /calhandlerforinvalidnames atch(eife="invalididexception"){ /calhandlerforinvalidids atch(eife="invalidemailexception"){ /calhandlerforinvalidemailadreses atch(e){/don'tknowhatodo,butlogit bad_name_handler(e) bad_id_handler(e) bad_email_handler(e) logeror(e) }c } Syntax pro práci s objekty for(propinobj){ s tatements }w ith(obj){ s tatements } Syntax (výjimky) throw{type:"userexception", mesage:"valuetohigh"}; try{statements1 atch(e){ tatements2 inaly{statements3 }c s}f }
Funkce aresult=newaray(ȧlength); for(vari=0;i<=ȧlength;i+) ap(function(x){returnx*x*x},[0,1,2]); functionobvod(a,b){ eturn2*(a+b); unctionmap(f,a){ result[i]=f(a[i]); eturnresult; functionf(x,y){ eturnargumentṡlength; r}f v }m r}f (0);f(0,"dog"); (0,"dog",false); f Syntax (středníky) zápis význam { 1 2 } 3 { 1 2 } 3 { 1 ;2 ;} 3; for (a; b ) return a + b return; a + b; a = b ++c a = b; ++c; if (a < b) else c = d a = b + c (d + e).print() a = b + c(d + e).print() Vestavěné funkce eval isfinite, isnan parseint, parsefloat Number, String escape, unescape, encodeuri, decodeuri, encodeuricomponent, decodeuricomponent Objekty ycar={make:"eagle",model:"talontsi"}; ycar=newcar("eagle","talontsi",193); unctioncar(make,model,year){ mycar={make:"eagle", odel:"talontsi", ear:193} mycaṙyear=193; eletemycaṙmodel; thiṡmake=make; hiṡmodel=model; hiṡyear=year; df t }m
neexistují třídy a jejich instance, pouze objekty každý objekt má prototyp (to je také objekt), pomocí prototypů je zajištěna dědičnost zápis obj.prop znamená hledání vlastnosti prop na objektu obj, v případě neúspěchu na jeho prototypu, v případě neúspěchu na prototypu jeho prototypu, atd. (až dokud poslední prototyp v řetězci není null)
}WorkerBėprototype=newEmploye; mployėprototypėname="unknown"; functionemploye(){ hiṡname="; hiṡdept="general"; }functionworkerbe(){ hiṡprojects=[]; amy=newworkerbe; te
unctionemploye(name,dept){ varidcounter=1; hiṡname=name "; hiṡdept=dept "general"; unctionmanager(name,dept,reports){.} functionworkerbe(name,dept,projs){.} thiṡid=idcounter+; Manageṙprototype=newEmploye; WorkerBėprototype=newEmploye; functionenginer(name,projs,mach){.} functionsalesperson(name,projs,quota){.} Engineṙprototype=newWorkerBe; SalesPersoṅprototype=newWorkerBe; mac=newenginer("wod,mac"); ft }f Array.prototype tostring() totéž, co join() tolocalestring() concat(item1, item2, ) join(separator) vytvoření řetězce (defaultní separátor je čárka) pop() push(item1, item2, ) reverse() shift() slice(start, end) functionemploye(){ hiṡdept="general"; }Employėprototypėname="; }WorkerBėprototype=newEmploye; mployėprototypėname="unknown"; functionworkerbe(){ hiṡprojects=[]; amy=newworkerbe; te Array vara=newaray(); arb=newaray(3); arc=newaray(3,"a"); vard=["a","b","c"]; v
Array.prototype sort(comparefn) splice(start, deletecount, item1, item2, ) unshift(item1, item2, ) Boolean new Boolean(value) Boolean.prototype tostring() vrátí "true", nebo "false" valueof() vrátí true, nebo false arb=newdate("december25,19513:30:0"); vard=newdate(195,1,25,9,30,0); Datėparse("December25,19513:30:0"); varc=newdate(195,1,25); DatėUTC(195,1,25,9,30,0); vara=newdate(); v Date Date.prototype tostring(), tolocalestring(), toutcstring() todatestring(), totimestring(), todatelocalestring(), todatetimestring() valueof() gettime(), getfullyear(), getutcfullyear(), getmonth(), getutcmonth(), gettimezoneoffset() rozdíl mezi místním časem a UTC v minutách settime(time), setmilliseconds(ms), setutcmilliseconds(ms),
Function new Function(arg1, arg2,, argn, functionbody) Function.prototype tostring() apply(obj, params) zavolá funkci a podstrčí jí obj jako její this call(obj, arg1, arg2, ) zavolá funkci a podstrčí jí obj jako její this Instance funkcí length očekávaný počet parametrů Math E, LN10, LN2, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 abs(x), acos(x), asin(x), atan(x), atan2(y, x), ceil(x), cos(x), exp(x), floor(x), log(x), max(value1, value2, ), min(value1, value2, ), pow(x, y), random(), round(x), sin(x), sqrt(x), tan(x) Number MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY Number.prototype tostring(radix), tolocalestring() valueof() tofixed(fractiondigits) toexponential(fractiondigits) toprecision(precision) RegExp new RegExp(pattern, flags) Instance regulárních výrazů source global ignore multiline lastindex
tostring() exec(string) test(string) RegExp.prototype RegExp.prototype.exec myre d(b+)(d)/ig; m yaray=myrėexec("cdbbdbsbz"); Object Property/ Index Description Example The contents of myarray. ["dbbd", "bb", "d"] index The 0-based index of the match in the string. 1 myarray input The original string. cdbbdbsbz [0] The last matched characters. dbbd [1], [2], The parenthesized substring matches, if any. The number of possible parenthesized [1] = bb substrings is unlimited. [2] = d lastindex The index at which to start the next match. 5 ignorecase Indicates if the i flag was used to ignore case. true myre global Indicates if the g flag was used for a global match. true multiline Indicates if the m flag was used for a multiline match. false source The text of the pattern. d(b+)(d) String new String(value) fromcharcode(char0, char1, ) Instance řetězců length String.prototype tostring(), valueof() charat(pos), charcodeat(pos) concat(string1, string2, ) indexof(searchstring, position), lastindexof(searchstring, position) localecompare(that) match(regexp) neglobální vrátí regexp.exec(str) globální vrátí pole nultých prvků výsledků postupných volání regexp.exec(str) replace(searchvalue, replacevalue) search(regexp) vrátí index nálezu
String.prototype slice(start, end) split(separator, limit) substring(start, end) tolowercase(), tolocalelowercase(), touppercase(), tolocaleuppercase() Odkazy Netscape Devedge JavaScript Central JavaScript 1.5 Guide JavaScript 1.5 Reference ECMAScript Language Specification