function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }
// testsconsole.log(whatAmI(["aiming","@"]),whatAmI({living:4,breathing:4}),whatAmI(function(ing){ return ing+" to the global window" }),whatAmI("going to do with you?"));
// output: Array Object Function String
然后你可以写一个简单的if语句…
if(whatAmI(myVar) === "Array"){// do array stuff} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure// do string stuff}
function isArray(h){if((h.length!=undefined&&h[0]!=undefined)||(h.length===0&&h[0]===undefined)){return true;}else{ return false; }}
我已经测试了这些数组(都返回true):
1) array=d.getElementsByName('some_element'); //'some_element' can be a real or unreal element2) array=[];3) array=[10];4) array=new Array();5) array=new Array();array.push("whatever");
function isArray(value) {if (value) {if (typeof value === 'object') {return (Object.prototype.toString.call(value) == '[object Array]')}}return false;}
var ar = ["ff","tt"]alert(isArray(ar))
var is_array = function (value) {return value &&typeof value === 'object' &&typeof value.length === 'number' &&typeof value.splice === 'function' &&!(value.propertyIsEnumerable('length'));};
/* Initialisation */Object.prototype.isArray = function() {return false;};Array.prototype.isArray = function() {return true;};Object.prototype._isArray = false;Array.prototype._isArray = true;
var arr = ["1", "2"];var noarr = "1";
/* Method 1 (function) */if (arr.isArray()) document.write("arr is an array according to function<br/>");if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");/* Method 2 (value) - **** FASTEST ***** */if (arr._isArray) document.write("arr is an array according to member value<br/>");if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");
var myAr = [1,2];
checkType(myAr);
function checkType(data) {if(typeof data ==='object') {if(Object.prototype.toString.call(data).indexOf('Array') !== (-1)) {return 'array';} else {return 'object';}} else {return typeof data;}}
if(checkType(myAr) === 'array') {console.log('yes, it is an array')};
function isArray(obj){return (typeof obj.push === 'function') ? true : false;}
var array = new Array();
or
var array = ['a', 'b', 'c'];console.log(isArray(array));
// this functions puts a string inside an arrayvar stringInsideArray = function(input) {if (typeof input === 'string') {return [input];}else if (Array.isArray(input)) {return input;}else {throw new Error("Input is not a string!");}}
var output = stringInsideArray('hello');console.log('step one output: ', output); // ["hello"]
// use typeof method to verify output is an objectconsole.log('step two output: ', typeof output); // object
// use Array.isArray() method to verify output is an arrayconsole.log('step three output: ', Array.isArray(output)); // true