TO REMIND ME OF BASIC SYNTAX IN THE 2 LANGS:
Javascript (JS), and PHP
(PHP ESSENTIAL)
OR = value?>
The latter needs no echo, no semicolon.
The value is then translated into a print string and echo-ed out.
**VARS
#PHP
$var1 case sensitive. BUT functions are case INsensitive.
Always local unless otherwise labelled i.e. do "global $var1" inside each fn
Can use globals in functions AND set them there: like static vars.
global ${$varname}; $currentval = ${$varname};
Also: $$a or ${$a} gets the string in $a and de-refs it to use it as the varname
Vars can NOT be init in the decl.
#JS
var1. Case sensitive, including functions?
Always global unless decl. locally. So keep doing "var var1;" inside each fn.
var count = 0, unset=1, prevDisp=0;
More exactly, vars and I think fn-args are textually scoped to the nearest
enclosing fn-def else global.
Games/features with closures ensue.
Fn-args are call by name or ref. depending on whether the object is primitive
or an object (in which case a ptr is passed, so call-by-ref is the effect).
**DOT NOTATION
#PHP
Dot operator is string concat.
#JS
+ operator is string concat.
Dot in JS is object fields/properties NOT fn-exec.
NOT: a.b.fn() is NOT fn(b(a));
BUT:
(a.b ==== a["b"] );
var name = 'b'; then a.b ==== a[name];
**ECHO
#PHP
echo is not a fn so can do either echo('asdf') or echo 'adsf';
echo 'asdf' . 'qr';
echo('asdf' . 'qr');
echo 'asdf', 'qr'; but not mulitple args AND parens.
#JS
No echo in JS; nearest is: document.write('Hello World!');
or alert(str);
---==========================================================
**IF conditionals
#PHP
if ($b) $a = 1;
$a = ($x > 0 ? 1 : 0); [Allowed]
$b AND $a=1;
if ($b) a = 1;
elseif ($b2) b=2;
else c=3;
if ($b):
$a = 1;
$a2 = 11;
elseif ($b2):
$b=2;
else:
$c=3;
endif;
#JS
if (b) a = 1;
a = (b > 0) ? 1 : 0; [Allowed]
y = (on) ? '' : 'none'; [Allowed]
The condition can be just on, (on), or (on==1)
BUT only (on == 1) may work if type conversions from string are
needed. (or else, use Number(on))
b && dothis(); N.B. JS returns the value of expr-part, not a boolean.
N.B. with the expr. you apparently CAN'T use parens to clarify, but can go on
and on with multiple exprs, like if-then-elseif-then-elseif....
if (b) a = 1;
else if (b2) b=2;
else c=3;
if (b) { x; y; z; }
else {a; b; c; }
**LOOPS while, etc.
#PHP
while ($b) { ... break/continue }; do { } while ($b);
#JS
while (b) { ... break/continue }; do { } while (b);
**forLOOPS
#PHP
for ($i=0; $i<=10; $i++)
#JS
for (var i=0; i<=10; i++) N.B. var anywhere in a func decls it as local; and
re-decls hae no effect; nor does order within the function.
**FOREACH
#PHP
foreach ($arr as $val) {} // when no, or implicit, index/keys
foreach ($GLOBALS as $key => $val) { echo "$key => $val
"; };
// for sorting array
$myorder = array_keys($arr);
natcasesort($myorder);
foreach ($myorder as $key) { $p = mktypegen($arr[$key], $key); };
#JS
There is no 'foreach' keyword.
for (var i = 0; i < arr.length; i++) { out = a[$i]; };
for (var key in object) {}
There is a forEach function, but not worth it:
var groups = ['agenda', 'mysmall']; // list of groups to init
groups.forEach(function (gr1) {
var = sessionStorage.getItem(gr1);
expand(gr1, val);
});
Just using function calls is simpler?: and writing a fn which you have to
do anyway in other forEach model.
function doPerclass(oneclass) {
var val = sessionStorage.getItem(oneclass);
expand(oneclass, val);
};
doPerclass('agenda');
doPerclass('mysmall');
...
JSON objects: alert(JSON.stringify(data, null, 4));
---==========================================================
**ARRAYs
#PHP
Arrays are assoc, or 'maps'.
$arr = array( k1 => v1, k2 => k2);
$arr = [ k1 => v1, k2 => k2];
#JS
Arrays are lists.
(But as objects, you can add sub-objects that behave like assocArrays).
var arr = [] to decl/init it as arr; arr.length=0 to re-zero it.
var arr = [3, 2, 'asdf']; inits it.
for (i=0; i if not spec.
**COMMENTS, SEMI-COLONS, QUOTES
#PHP
// comment
# comment
/* also comment text, and across lines
*/
Semicolons: mostly required (except at end of ?> )
$str = 'x
yz'; // no var expansion, may include LFs.
$str = "Here is \$var: $var \n"; [?? check this]
//Nowdoc facility, like in csh: uses quote type to ctrl the processing if any
inside.
$x = <<<'LABEL'
any old text
LABEL
#JS
// comment
/*
also comment text
*/
Either or ';' end a statement.
Single and double quotes mean the same; so can use one to quote the other;
esp. e.g. when string contains something to go into another lang.
**STRING edits
#PHP
$url = preg_replace('|[^/]$|', '${0}Y', $url);
Always does global replace, unless arg4 sets nmb of replaces.
$out = str_replace('TGT', $replaceStr, $orig, $nmbDone); no REs.
If used, arg4 must be var, and receives a count of replacements.
To limit nmb of replaces within a string, must use preg_replace
OR could use truncate instead.
Truncate
$rest = substr("abcdef", -3, 1) -3 means 3rd back from last char.
$rest = substr($buf, $start, $len) Start at var2, delete Len chars
$rest = substr($buf, 2, 999) Start at char 2, keep all the rest.
#JS
picPtr.src = picPtr.src.replace(',', ''); Not global but first occurrence
OR picPtr.src = picPtr.src.replace(/,/g, '');
i.e. it takes either a string OR an RE as arg1
if (/,/.test(str)) { DOES work
REGEXPs
#PHP
#JS
Can create REs by either/or:
var re = new RegExp(string + 'literalStr');
var re = /Any string\b/i;
//which lets you put literal with meta-chars, but not vars.
Where var group = 'group33'; and should be appended by metachar \b ...
re1 = /group33\b/i;
re2 = new RegExp(group + '\\b');
re3 = new RegExp(group + /\b/.source);
and RE used: if (re2.test(ruletxt)) where ruletxt is a string var.
**STRING cmps
#PHP
$s1 == $s2 equal after type conversions
$s1 === $s2 equal and same type
== === != <> !== < >= all work.
Strings are converted to numbers if necessary or appropriate. E.g. "10" == "1e1"
if (preg_match('/,del/', $f)) continue; // so more cmps of strings ...
if (preg_match('/^\d{4}$/', $id) == 0) // If doesn't match then ...
if (preg_match('/^[a-z]+$/i', $id) == 0) // If doesn't match alpha, then ...
$new = str_replace($target, replace, $orig, &$count); case-sensitive.
$new = str_ireplace($target, replace, $orig); case-insensitive.
Can give arrays for multiple find/replace pairs.
Only fixed strings.
$count receives a value for nmb of replaces done.
$new = preg_replace(pat, replacement substr, orig, $limit = -1, $nmbChanged)
$new = preg_replace(pat, '${1}00, $3', $origbuf, $limit = -1, $nmbChanged)
Returns null for error; unchanged orig if no match, changed if match.
If $limit pos, then max nmb changes.
I show use of replacements by subpatterns
preg_match(pat, orig, &$matches)
returns 1 or 0: whether any match.
$matches[0] the text of the match. [1] the first subpat, ...
$nmatches = preg_match_all(pat, orig, &$matches);
gets all matches and puts them in array.
$matches[1][3] has 4th match to 1st () sub-pat. [0] is whole pat.
flags change what goes where in the arrays.
#JS
Ditto? Strings are objects (built-in).
OR only == if same object??
If you add a nmb and a string, it gives a string.
var n=str.match(/ain/gi); Returns an array of matches
Can test for match with simple if:
if (! /,/.test(str)) { DOES work: both the expr AND with the bool negation
if (picPtr.src.match(/,/)) DOESN'T work
var regex = new RegExp(myconstant);
string.replace(regex, "replacement");
if (! regex.test(str)) {
var str2=str.replace("Microsoft","W3Schools");
http://www.w3schools.com/jsref/jsref_obj_string.asp DOC for string fns
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
**PTR UNDEF TESTS
#PHP
empty($x) true if either not there or false (or zero integer)
isset($x) false if either not there or set to null.
is_null($x) true if not set to anything (except null).
defined($x) constant is defined. Only for constants, it says.
#JS
Objects are null; vars/props are undefined.
Vars (& attributes) that have not been assigned a val,
are of type undefined.
if (typeof var1 === 'undefined') not decl. (but null).
if (obj.prop === undefined) has never been assigned a val. [triple ===]
if (obj.prop) To test it's decl, and assigned, and non-zero/false
var hasProperty = !!obj.prop; This creates a bool from ptr.
if (isNaN(obj.colSpan)) tests that the var/attribute is: not undefined and is a
number (as opposed to some other, or null, or empty value).
To delete properties:
delete myObject.keyname; or delete myObject["keyname"];
http://perfectionkills.com/understanding-delete/
but cannot delete variables decl. as var x; nor functions.
** TYPE AND NUMBER CONVERSIONS
#PHP
intval($var), floatval($var), (int) "123";
strval($var) But use sprintf() to control formatting.
#JS
var n = parseInt(str); parseFloat() // if (isNaN(n))..
var n = Number(str); // if (isNaN(n))..
var str = n.toString();
var str2 = 'opacity: 0.' + n.toString() + ';');
var marginpc = Math.round((100 - widthpc) / 4);
** URL OBJECTS AND FS
#PHP
xxx
#JS
window.location.href gets full URL of current page/window.
document.URL; does same but may not work in Firefox
document.getElementById("aaa").getAttribute("href");
Gets text as set in the 'href' field of, say, an element.
window.location gets url as a whole object, ready-parsed into URL parts
(see below).
For current page, window.location gets a "location object", with ready-defined
parts: hash(part after #), host (includes port), hostname, href (whole thing),
origin, pathname, port, protocol, search (part after?).
Can set the location by setting the href field even if it is a partial /
relative URL.
Parsing function, given a whole URL:
1) if possible, use location object's pre-parsing.
2) DIY using split() var pathArray = window.location.pathname.split( '/' );
To get an abs URL out of a relative one, here's code I haven't tested.
It defines a function then calls it.
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();