How to check if an object is an array?

后端 未结 30 2888
名媛妹妹
名媛妹妹 2020-11-21 06:31

I\'m trying to write a function that either accepts a list of strings, or a single string. If it\'s a string, then I want to convert it to an array with just the one item so

30条回答
  •  臣服心动
    2020-11-21 07:16

    This function will turn almost anything into an array:

    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]"
    }
    

    It uses some newer browser features so you may want to polyfill this for maximum support.

    Examples:

    > 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. strings will be converted into an array with a single element instead of an array of chars. Delete the isString check if you would prefer it the other way around.

    I've used Array.isArray here because it's the most robust and also simplest.

提交回复
热议问题