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

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


当前回答

这是我的懒惰方法:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

我知道“搞乱”原型是一种亵渎,但它的性能明显优于推荐的toString方法。

注意:这种方法的一个缺点是它不能跨iframe边界工作,但对于我的用例来说,这不是问题。

其他回答

ECMAScript标准中给出的查找Object类的方法是使用Object.prototype中的toString方法。

if(Object.prototype.toString.call(someVar) === '[object Array]') {
    alert('Array!');
}

或者您可以使用typeof来测试它是否为字符串:

if(typeof someVar === 'string') {
    someVar = [someVar];
}

或者,如果您不关心性能,您可以直接连接到一个新的空数组。

someVar = [].concat(someVar);

还有可以直接查询的构造函数:

if (somevar.constructor.name == "Array") {
    // do something
}

查看T.J.Crowder的博客中的彻底治疗,如他在下面的评论中所述。

查看此基准测试,了解哪种方法性能更好:http://jsben.ch/#/QgYAV

从@Bharath,使用ES6将字符串转换为数组,以回答以下问题:

const convertStringToArray = (object) => {
   return (typeof object === 'string') ? Array(object) : object
}

假设:

let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
 var length = 16;                               // Number
 var lastName = "Johnson";                      // String
 var cars = ["Saab", "Volvo", "BMW"];           // Array
 var x = {firstName:"John", lastName:"Doe"};

 Object.prototype.myCheck= function(){
 if (this.constructor === Array){
          alert('array');
        }else if (this.constructor === Object)
       {
         alert('object');
        }else if (this.constructor === Number)
        {
          alert('number');
        }else if (this.constructor === String)
        {
          alert('string');
        }

 }
 cars.myCheck();
 lastName.myCheck();
 length.myCheck();

也存在其他方法来检查,但我更喜欢以下方法作为我的最佳检查方法(因为您可以轻松检查其他对象的类型)。

> a = [1, 2]
[ 1, 2 ]
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>
> Object.prototype.toString.call([]).slice(8,-1) // best approach
'Array'

解释(节点REPL上的简单示例)»

> o = {'ok': 1}
{ ok: 1 }
> a = [1, 2]
[ 1, 2 ]
> typeof o
'object'
> typeof a
'object'
>
> Object.prototype.toString.call(o)
'[object Object]'
> Object.prototype.toString.call(a)
'[object Array]'
>

对象或阵列»

> Object.prototype.toString.call(o).slice(8,).replace(/\]$/, '')
'Object'
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>

空或未定义»

> Object.prototype.toString.call(undefined).slice(8,).replace(/\]$/, '')
'Undefined'
> Object.prototype.toString.call(null).slice(8,).replace(/\]$/, '')
'Null'
>

字符串»

> Object.prototype.toString.call('ok').slice(8,).replace(/\]$/, '')
'String'

编号»

> Object.prototype.toString.call(19).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.0).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.7).slice(8,).replace(/\]$/, '')
'Number'
>

我很感谢@mpen建议使用-1代替正则表达式,如下所示。

> Object.prototype.toString.call(12).slice(8,-1)
'Number'
>
> Object.prototype.toString.call(12.0).slice(8,-1)
'Number'
>
> Object.prototype.toString.call([]).slice(8,-1)
'Array'
> Object.prototype.toString.call({}).slice(8,-1)
'Object'
>
> Object.prototype.toString.call('').slice(8,-1)
'String'
>

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()。

我见过的最佳解决方案是用跨浏览器替换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 */};