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

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


当前回答

Stoyan Stefanov的《JavaScript模式》一书中有一个很好的例子,它应该处理所有可能的问题,并使用ECMAScript 5方法Array.isArray()。

这里是:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}

顺便说一下,如果使用jQuery,可以使用其方法$.isArray()。

其他回答

我首先检查您的实现是否支持isArray:

if (Array.isArray)
    return Array.isArray(v);

也可以尝试使用instanceof运算符

v instanceof Array

在您的情况下,您可以使用Array的concat方法,它可以接受单个对象,也可以接受数组(甚至组合):

function myFunc(stringOrArray)
{
  var arr = [].concat(stringOrArray);

  console.log(arr);

  arr.forEach(function(item, i)
  {
    console.log(i, "=", item);
  })
}

myFunc("one string");

myFunc(["one string", "second", "third"]);

concat似乎是Array最古老的方法之一(即使是IE 5.5也很熟悉)。

我见过的最佳解决方案是用跨浏览器替换typeof。检查Angus Croll的解决方案。

TL;DR版本在下面,但这篇文章对这个问题进行了很好的讨论,所以如果您有时间,应该阅读它。

Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)

// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};
var a = [], b = {};

console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");

Use:

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

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