经常在写javascript代码的时候,想起php某些函数的功能,总觉得javascript也要这些函数就好了。比如intval之类的,当然也可以自己写函数来实现。后来在网上逛的时候,发现了还真有人在做这个事情。
这个是作者的博客:http://kevin.vanzonneveld.net/techblog/category/php2js/
他的这个js函数库已经在js中实现了大多数php常见函数功能,试了一下,还是很不错的,如果你跟我由同样的需求,不妨看看他的博客。
他的javascript的intval实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| // {{{ intval
function intval( mixed_var, base ) {
// Get the integer value of a variable
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_intval/
// + version: 812.3015
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: stensi
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: intval('Kevin van Zonneveld');
// * returns 1: 0
// * example 2: intval(4.2);
// * returns 2: 4
// * example 3: intval(42, 8);
// * returns 3: 42
// * example 4: intval('09');
// * returns 4: 9
var tmp;
var type = typeof( mixed_var );
if(type == 'boolean'){
if (mixed_var == true) {
return 1;
} else {
return 0;
}
} else if(type == 'string'){
tmp = parseInt(mixed_var * 1);
if(isNaN(tmp) || !isFinite(tmp)){
return 0;
} else{
return tmp.toString(base || 10);
}
} else if(type == 'number' && isFinite(mixed_var) ){
return Math.floor(mixed_var);
} else{
return 0;
}
}// }}} |
php.js下载:
php.js (554.2 KiB, 50 hits)