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

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


当前回答

首先,您可以检查console.log(对象类型)。

如果输出是对象,则var{data}=对象,即根据对象键销毁对象。

函数可以是这样的:

const abc = (str1, str2=null) => {
    var result = [];
    result.push(str1);
    result.push(str2);
    return result.join("");
}

其他回答

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

函数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
}

Array.isArray工作速度很快,但并非所有版本的浏览器都支持它。

因此,您可以为其他人创建例外,并使用通用方法:

    Utils = {};
    Utils.isArray = ('isArray' in Array) ?
        Array.isArray :
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }

首先,您可以检查console.log(对象类型)。

如果输出是对象,则var{data}=对象,即根据对象键销毁对象。

函数可以是这样的:

const abc = (str1, str2=null) => {
    var result = [];
    result.push(str1);
    result.push(str2);
    return result.join("");
}

此函数将几乎所有内容转换为数组:

function arr(x) {
    if(x === null || x === undefined) {
        return [];
    }
    if(Array.isArray(x)) {
        return x;
    }
    if(isString(x) || isNumber(x)) {
        return [x];
    }
    if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
        return Array.from(x);
    }
    return [x];
}

function isString(x) {
    return Object.prototype.toString.call(x) === "[object String]"
}

function isNumber(x) {
    return Object.prototype.toString.call(x) === "[object Number]"
}

它使用了一些较新的浏览器功能,因此您可能需要对其进行多填充以获得最大支持。

示例:

> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]

N.B.字符串将被转换为具有单个元素的数组,而不是字符数组。如果您希望使用其他方式,请删除isString复选框。

我在这里使用了Array.isArray,因为它是最健壮的,也是最简单的。

正如MDN在这里所说:

使用Array.isArray或Object.prototype.toString.call进行区分阵列中的常规对象

这样地:

Object.pr原型.toString.call(arr)==“[对象数组]”,或Array.isArray(arr)