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

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


当前回答

下面是一段代码片段,它将解释数组的一个重要事实,在学习JavaScript时应该尽早了解这些事实(与我不同)。

//此函数将字符串放入数组中var stringInsideArray=函数(输入){if(输入类型==“string”){返回[输入];}else if(Array.isArray(输入)){返回输入;}其他{throw new Error(“输入不是字符串!”);}}var output=stringInsideArray('hello');console.log('第一步输出:',输出);//[“你好”]//使用typeof方法验证输出是否为对象console.log('第二步输出:',输出类型);//对象//使用Array.isArray()方法验证输出是否为数组console.log('第三步输出:',Array.isArray(输出));//真的

数组实际上是对象。

使用typeof运算符,stringInsideArray('hello')的输出证明[“hello”]确实是一个对象。这让我困惑了很长一段时间,因为我假设数组是JavaScript数据类型。。。

只有七种JavaScript数据类型,数组不是其中之一。

要回答您的问题,请使用Array.isArray()方法确定输出是一个数组。

其他回答

我做这件事的方式很简单。这对我有用。

Array.prototype.isArray = true;

a=[]; b={};
a.isArray  // true
b.isArray  // (undefined -> false)

我会制作一个函数来测试您正在处理的对象的类型。。。

函数whatAmI(me){return Object.pr原型.toString.call(me).split(/\W/)[2];}//测试控制台日志(whatAmI([“瞄准”,“@”]),whatAmI({生活:4,呼吸:4}),whatAmI(函数(ing){return ing+“到全局窗口”}),我(“要和你做什么?”));//输出:数组对象函数字符串

然后你可以写一个简单的if语句。。。

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}

isArray(obj)没有提供非常有用的结果。我已经创建了一个Object的原型方法,它似乎可以正确地确定和对象是否是数组。

我所知道的唯一失败的边缘情况是数组中的项设置为undefined。

Object.prototype.isArrayLike = function()
{
    var length = this.length || Object.keys(this).length;
    if (length === 0 || this.constructor.name === "String")
        return false;
    for (i = 0; i < length; i++)
    {
        if (typeof this[i] === "undefined")
            return false;
    }
    return true;
};

var arr = ['aaa', 'bbb', 'ccc', 'ddd'];
var arr1 = {"0":'aaa', "1":'bbb', 2:'ccc', 3:'ddd'};
var arr2 = {"0":'aaa', "a":'bbb', 2:'ccc', 3:'ddd'};
var arr3 = "qwerty";
var arr4 = [];
var arr5 = {0:'aaa', 1:'bbb', 2:'ccc', 3:'ddd'};

console.log("arrayLike:" + arr.isArrayLike());
console.log("Array.isArray(arr):" + Array.isArray(arr));
// arrayLike: true
// Array.isArray(arr): true
console.log("arrayLike1:" + arr1.isArrayLike());
console.log("Array.isArray(arr1):" + Array.isArray(arr1));
// arrayLike1: true
// Array.isArray(arr1): false
console.log("arrayLike2:" + arr2.isArrayLike());
console.log("Array.isArray(arr2):" + Array.isArray(arr2));
// arrayLike2: false
// Array.isArray(arr2): false
console.log("arrayLike3:" + arr3.isArrayLike());
console.log("Array.isArray(arr3):" + Array.isArray(arr3));
// arrayLike3: false
// Array.isArray(arr3): false
console.log("arrayLike4:" + arr4.isArrayLike());
console.log("Array.isArray(arr4):" + Array.isArray(arr4));
// arrayLike4: false
// Array.isArray(arr4): true
console.log("arrayLike5:" + arr5.isArrayLike());
console.log("Array.isArray(arr5):" + Array.isArray(arr5));
// arrayLike5: false
// Array.isArray(arr5): true

你可以试试这个:

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

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

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

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