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

前端 未结 7 1466
南旧
南旧 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:18

    If you want to check whether an array x exists and create it if it doesn't, you can do

    x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []
    
    0 讨论(0)
  • 2020-12-07 22:19

    You can use the typeof operator to test for undefined and the instanceof operator to test if it’s an instance of Array:

    if (typeof arr == "undefined" || !(arr instanceof Array)) {
        var arr = [];
    }
    
    0 讨论(0)
  • 2020-12-07 22:22
    <script type="text/javascript">
    
    array1  = new Array('apple','mango','banana');
    var storearray1 =array1;
    
    if (window[storearray1] && window[storearray1] instanceof Array) {
        alert("exist!");
    } else {
        alert('not find: storearray1 = ' + typeof storearray1)
        }
    
    </script>   
    
    0 讨论(0)
  • 2020-12-07 22:24

    If you want to check if the object is already an Array, to avoid the well known issues of the instanceof operator when working in multi-framed DOM environments, you could use the Object.prototype.toString method:

    arr = Object.prototype.toString.call(arr) == "[object Array]" ? arr : [];
    
    0 讨论(0)
  • 2020-12-07 22:27
    var arr = arr || [];
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题