我正在尝试编写一个函数,它要么接受字符串列表,要么接受单个字符串。如果它是一个字符串,那么我想把它转换成一个只有一个项的数组,这样我就可以在上面循环,而不用担心出错。

那么如何检查变量是否为数组?


当前回答

Array.isArray是实现这一点的方法。例如:

var arr = ['tuna', 'chicken', 'pb&j'];
var obj = {sandwich: 'tuna', chips: 'cape cod'};

// Returns true
Array.isArray(arr);

// Return false
Array.isArray(obj);

其他回答

如果您知道对象没有concat方法,可以使用以下方法。

var arr=[];if(arr.concat类型==“函数”){console.log(“这是一个数组”);}

检查此项的简单函数:

function isArray(object)
{
    return object.constructor === Array;
}

Use:

var is_array = function (value) {
   return value &&
     typeof value === 'object' &&
     typeof value.length === 'number' &&
     typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

这个函数取自《JavaScript:TheGoodParts》一书,非常适合我。

你可以试试这个:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false

您可以检查变量的类型是否为数组;

var myArray=[];

if(myArray instanceof Array)
{
....
}