1 Objects
movie = {title: 'The Godfather',
'releaseInfo': {'year': 1972, rating: 'PG'}}
//Access an object's properties
movie.title
movie['title']
//iterates over obj's property names in arbitrary order
for (var in obj){. . . }
2 Types
typeof(x)
returns x's primitive type
// one of "object", "string", "array", "number", "boolean", "function", "undefined".
// All numbers are doubles.
2.1 Strings
"string", 'also a string', 'joining'+'strings'
'mad, mad world'.split(/[, ]+/) == ["mad","mad","world"]
'mad, mad world'.slice(3,4)==", mad";
'mad, mad"
"world".slice(-3)=="rld"
'mad'.indexOf('d')==2,
'mad'.charAt(2)=='d',
'mad'.charCodeAt(4)==100,
'mad'.replace(/(\w)$/,'$1$1er')=="madder"
2.2 Regexps
//Regexps /regexp/.exec(string) if no match returns null, if match returns array whose zeroth element is whole string matched and additional elements are parenthesized capture groups. "
// Alternate constructor
new RegExp('[Hh]e(l+)o')
2.3 Arrays
//Zero-based, grow dynamically; objects whose keys are numbers
arr.sort(function (a,b) {. . . }) Function returns -1, 0 or 1
var a = [1, {two: 2}, 'three'] ; a[1] == {two: 2}
for a < b, a == b, a > b
2.4 Numbers
- / %, also +=, etc., ++ --, Math.pow(num,exp)
Math.round(n),
Math.ceil(n),
Math.floor(n)
// round their argument to nearest, higher, or lower integer respectively
Math.random() returns a random number in (0,1)
2.4 Conversions
'catch'+22=='catch22',
'4'+11==15,
'4'+'11'=='411'
parseInt('4oneone')==4,
parseInt('four11')==NaN // !!! parseInt('four11')是NaN,但不等于NaN。。。 NaN != NaN。。。多谢5楼指正!
parseInt('0101',10)==101,
parseInt('0101',2)==5,
parseInt('0101')==65
// (numbers beginning with 0 are parsed in octal by default, unless radix is specified)parseFloat('1.1b23')==1.1, parseFloat('1.1e3')==1100"
2.5 Booleans
false, null //(like Ruby nil)
undefined // (undefined value, different from null),
0,
''// the empty string
NaN // (not-a-number)
are falsy (Boolean false)
true and all other expressions are truthy.
3 Naming localVar, local_var, ConstructorFunction, GLOBAL All are conventions; JavaScript has no specific capitalization rules. var keyword scopes variable to the "function" in which it appears, otherwise it becomes a global (technically, a property of the global object. Variables don't have types, but the objects they refer to do }
4 Control flow
while, for(;;),
if/else if/else,
? : (ternary operator),
switch/case,
try/catch/throw,
return,
break
// Statements separated by semicolons; interpreter tries to auto-insert "missing" ones, but this is perilous.