How to convert array or string to array in JavaScript?

This question already has an answer here:

  • Check if object is array? 38 answers

  • EDIT:

    As @Jaromanda X pointed out in the other answer you can use concat:

    var result = [].concat(aFunction());
    

    kudos!


    I don't think there is a way to do this without an if, so just check if the output is a String and, in case, add it to an empty array.

    var result = myFn();
    if (typeof result === 'string' || result instanceof String) {
        result = new Array(result);
    }
    

    使用数组concat函数

    var arr = [].concat(aFunction());
    

    没有“ 如果 ”;)(但在内部三元运算符正在做if / else的东西)

    var result = aFunction();
    result = (typeof result == "string") ? [result] : result;
    
    链接地址: http://www.djcxy.com/p/27570.html

    上一篇: 在JavaScript中如何检测天气的类型是数组还是对象?

    下一篇: 如何将数组或字符串转换为JavaScript中的数组?