How to create an array if an array does not exist yet?

前端 未结 7 1468
南旧
南旧 2020-12-07 21:43

How do I create an array if it does not exist yet? In other words how to default a variable to an empty array?

7条回答
  •  [愿得一人]
    2020-12-07 22:37

    const list = Array.isArray(x) ? x : [x];
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

    Or if x could be an array and you want to make sure it is one:

    const list = [].concat(x);
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

提交回复
热议问题