JS版的in_array和is_array
写PHP代码是我们可以使用is_array()方法来检测一个变量是否是数组,使用in_array()来判断一个变量是否包含在一个数组中,那么在JS中我们该,如何来判断呢?
下面来分享下,js的方法is_array:
1 |
//检测一个变量是否是数组 |
2 |
function is_array(v){ |
3 |
return toString.apply(v) === '[object Array]' ; |
4 |
} |
01 |
//检测一个变量是否在一个数组中 |
02 |
//needle 待检测字符串 |
03 |
//haystack 数组或者是以|分割的字符串 |
04 |
function in_array(needle,haystack) { |
05 |
haystack=is_array(haystack)?haystack:haystack.split( "|" ); |
06 |
if ( typeof needle == 'string' || typeof needle == 'number' ) { |
07 |
for ( var i in haystack) { |
08 |
if (haystack[i] == needle) { |
09 |
return true ; |
10 |
} |
11 |
} |
12 |
} |
13 |
return false ; |
14 |
} |