全栈工程师看过来!PHP Javascript语法对照、速查

全栈工程师看过来!PHP Javascript语法对照、速查,第1张

全栈工程师看过来!PHP Javascript语法对照、速查

PHP、JavaScript 语法对照、速查

全栈工程师看过来,学的计算机语言多了,往往会把不同语言的各个函数搞混。作为一个全栈PHPer,往往PHP、JavaScript 语法傻傻分不清楚,百度一下,查手册要网速。不如收藏下这篇文章,打印出来,贴到一旁快速查阅。

相关推荐:《PHP视频教程》《javascript高级教程》

JavaScript 的一些数组map函数有jQuery实现,ES6后,又出了官方实现。PHP 的数组、字符串相关函数的命名随性,这仨一块就更容易混淆了。

编码风格语言PHPJavaScript换行; 号是必须的,\n不是必须的换行 \n,以及 ; 号都不是必须的,for(;;)除外大小写敏感度只有变量名区分大小写变量名、函数名、类名等 都区分大小写严格模式declare(strict_types=1); (PHP7新特性)“use strict”;(ECMAScript 5 引入)变量声明语言PHPJavaScript常量const VAR_NAME = 12;
define(‘VAR_NAME’, 12);const MY_FAV = 7; (ES6引入的标准)局部变量$varName = 12; (PHP只有函数作用域,和全局作用域之分)function myFunc() {
var varName = 3;
if (true) {
let varName2 = 2;
}
}
(函数作用域内必须用var声明,否则变量全局可访问.)
(let修饰的变量就是块级别作用域,ES6引入)
全局变量$varName = 12;
function myFunc() {
global $varName;
}
(函数内使用全局变量,必须要用global变量声明使用外部的全局变量)var varName1 = 3;
varName2 = 2;
function myFunc() {
varName3 = 6;
} (这里写法varName1,2,3都是全局变量)全局符号表$GLOBALS 数组window 对象(html环境中)
global 对象(nodejs环境)为定义变量nullundefined变量转换语言PHPJavaScript转bool,boolean$bar = (boolean) $foo;
$bar = (bool) $foo;
$bar = boolval($foo);boolVal = Boolean(‘’)转 int$bar = (int) $foo;
$bar = (integer) $foo;
$bar = intval($foo);intVal = Number(“314”)
intVal = parseInt(“3.14”)转 float$bar = (float) $foo;
$bar = (double) $foo;
$bar = (real) $foo;
$bar = floatval($foo);floatVal = Number(“3.14”)
flotaVal = parseFloat(“12”)转换为 string$bar = (string) $foo;
$bar = strval($foo);str = String(123)
str = (123).toString()转换为 array$arr = (array) new stdClass();(需要多行函数完成)转换为 对象$obj = (object) array(‘1’ => ‘foo’);let arr = [‘yellow’, ‘white’, ‘black’];
let obj = {…arr}时间戳转日期$date = new DateTime();
$date->setTimestamp(1171502725);var date = new Date(1398250549490);字符转日期$dateObj = new DateTime($dateStr);var myDateObj = new Date(Date.parse(datetimeStr))转换为 空(unset) $var; \ 不会删除该变量或 unset 其值。仅是返回 NULL 值而已
获取类型$varType = gettype($var);varType = typeof myCar类判断$boolRe = $a instanceof MyClass;boolRe = a instanceof MyClass
new Date().constructor === Date魔法变量语言PHPJavaScript当前文件$filePath = __FILE__;filePath = __filename当前目录$currentDir = __DIR__;curDir = __dirname当前代码行__LINE__
当前函数__FUNCTION__
当前类__CLASS__
当前命名空间__NAMESPACE__
运算符语言PHPJavaScript三目(三元)运算$a = $a ? $a : 1;//第一种
$a = $a ? : 1;//第二种 PHP5.3支持re = isMember ? 2.0 : ‘$10.00’合并运算符$a = $a ?? 1; // PHP7支持
数组语言PHPJavaScript基本$a=array(0 => 1, 1 => 2,4,5,6);
$array = [ “foo” => “bar”, “bar” => “foo”]; // PHP 7语法b = [1,2,3]追加$arr = array();
$arr[key1] = value1;
$arr[key2] = value2;var mycars=new Array()
mycars[0]=”Saab”
mycars[1]=”Volvo”
mycars[2]=”BMW”new
var mycars = new Array(“Saab”,”Volvo”,”BMW”)循环语言PHPJavaScriptfor 循环for ($i=1; $i<=5; $i++)
{
echo $i ;
}
for (var i=0; i < cars.length ; i++)
{
document.write(cars[i]);
}foreach ,for in 循环$x=array(“one”,”two”,”three”);
foreach ($x as $value) {
echo $value;
}var person= {fname:”John”,lname:”Doe”,age:25};
for (x in person) {
txt=txt + person[x];
}while 循环while ($i <= 5) {
echo $i ;
$i++;
}while (i<5) {
x=x + “num is “ + i ;
i++;
}do while 循环do {
$i++;
echo $i;
} while ($ i<= 5);do {
console.log(i);
i++;
} while (i < 5);数组函数语言PHPJavaScript获取数组中元素的数目count($arr);arrayObject.length拼接两个字符串array_merge($arr1, $arr2);arr1.concat(arr2)删除数组元素unset($arr[$key]);delete arr1[key]将数组拼接成字符串implode(‘,’, $arr1);arr.join(‘,’)删除并返回数组最后元素$re = array_pop($arr1);re = arrayObject.pop()向数组的末尾添加一个元素array_push($arr1, $var1);len = arrayObject.push(newele1)将数组的第一个元素删除并返回$re = array_shift($arr1);re = arrayObject.shift()向数组的开头添加一个或更多元素array_unshift($arr1, $var1);len = arrayObject.unshift(newele1)从已有的数组中返回选定的元素$newArr = array_splice($arr1,$start,$len);newArr = arrayObject.slice(start,end)排序sort($arr1);arrayObject.sort(sortByFunc = null)颠倒数组中元素的顺序array_reverse(&$arr, $keepKeys = true);arrayObject.reverse()


each 函数function map_Spanish($n)
{
echo $n;
}
$b = array(“uno”, “dos”, “tres”, “cuatro”, “cinco”);
$c = array_map(“show_Spanish”, $a);$.each([ 52, 97 ], function( index, value ) {
alert( index + “: “ + value );
});
// ↑ 这是 jQuery 方式
const items = [‘item1’, ‘item2’, ‘item3’];
items.forEach(function(item, index, arr){
console.log(‘key:’ + index + ‘ value:’ + item);
});
(ES6引入)回调函数迭代地将数组简化为单一的值function sum($carry, $item) {
$carry += $item;
return $carry;
}
$a = array(1, 2, 3, 4, 5);
var_dump(array_reduce($a, “sum”)); // int(15)var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
console.log(numbers.reduce(getSum));
始于ECMAScript 3用回调函数过滤数组中的单元function odd($var) {
// returns whether the input integer is odd
return($var & 1);
}
$array1 = array(“a”=>1, “b”=>2, “c”=>3, “d”=>4, “e”=>5);
echo “Odd :\n”;
array_filter($array1, “odd”);function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); \\ JavaScript 1.6 引入字符语言PHPJavaScript创建$str = “a string”;
\\比较特殊的是PHP在双引号字符中可以解析变量
$str2 = ‘tow string’;var carname = “Volvo XC60”;
var carname = ‘Volvo XC60’;
(同样的在双引号中可以使用转义字符)多行字符$bar = <<<EOT
foo
bar
EOT;
var tmpl =’\
!!! 5\
html\
include header\
body\
include script’字符拼接$str1 . $str2str1 + str2字符串函数语言PHPJavaScript获取字符长度strlen($str);string.length获取子字符串substr ( string $string , int $start [, int $length ] ) : stringstring.substr(start,length)
str.slice(1,5);使用一个字符串分割另一个字符串$pizza = “piece1 piece2 piece3 piece4 piece5 piece6”;
$pieces = explode(“ “, $pizza);
echo $pieces[0]; // piece1var str=”How are you doing today?”;
var n=str.split(“ “);
\ output:How,are,you,doing,today?去除字符串首尾处的空白字符(或者其他字符)trim ( string $str [, string $character_mask = “ \t\n\r\0\x0B” ] ) : string
(PHP 函数的可定制要强一点)var str = “ string “;
alert(str.trim());查找字符串首次出现的位置$mystring = ‘abcsdfdsa’;
$pos = strpos($mystring, ‘cs’);var str=”Hello world, welcome to the universe.”;
var n=str.indexOf(“welcome”);把字符串转换为小写strtolower ( string $string ) : stringstring.toLowerCase()把字符串转换为大写strtoupper ( string $string ) : stringstring.toUpperCase()函数语言PHPJavaScript函数参数$argv = func_get_args ( void );var argv = arguments \ 直接一个函数内对象对象语言PHPJavaScript空对象$obj = new stdClass();var obj = new Object(); // 或者
person={firstname:”John”,lastname:”Doe”,age:50,eyecolor:”blue”};对象属性$obj = new stdClass();
$obj->a = 12;var myCar = new Object();
myCar.year = 1969; // js还可以以数组形式
myCar[“year”] = 1969;删除属性unset($obj->a);delete object.property
delete object[‘property’]正则语言PHPJavaScript创建正则表达式$pattern = “/.*/i”;var re = /ab+c/;PCRE 正则int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )var myRe = /d(b+)d/g;
var myRe = new RegExp(“d(b+)d”, “g”);POSIX 正则ereg ( string $pattern , string $string [, array &$regs ] ) : int(无)数学函数语言PHPJavaScript随机函数$re = mt_rand($min, $max); // 返回 min~max 之间的随机整数Math.random() // 返回 0 ~ 1 之间的随机数x的y次方pow(x,y)Math.pow(x,y)包、空间语言PHPJavaScript命名空间namespace MySpace;(无)引入包use Package;
use Package as Package1, Package2;const http = require(‘http’) (CommonJS规范)
import “my-module”;
import {foo as fo, bar} from “my-module”;
(es6实现,import需要和export配合使用)引入文件include ‘b.php’;
require ‘bc.php’;<script type='text/javascript' src='b.js'></script> (仅在html中用)其他语言PHPJavaScript展开,可变函数function add(…$numbers) {
foreach ($numbers as $n) {
$sum += $n;
}
}
echo add(1, 2, 3, 4); // PHP5.6 开始支持function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(…args); (ES6开始支持)解构$my_array = array(‘a’=>’Dog’,’b’=>’Cat’,’c’=>’Horse’);
list($a, $b, $c) = $my_array;
// php5, 如果是php7版本支持以下语法
[‘a’=>$a, ‘c’=>$c] = $my_array;var date1 = [1970, 2, 1];
[ year, mouth ]= date1;
var date2 = {year: 1980, mouth: 3, day: 21};
({ mouth } = date2);
console.log(date1);
console.log(year);
console.log(mouth);

欢迎大家收藏,如果你觉得需要补充的地方,请留言。

以上就是全栈工程师看过来!PHP Javascript语法对照、速查的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/685535.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存