简体   繁体   中英

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

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

如果你想检查一个数组 x 是否存在,如果不存在就创建它,你可以这样做

x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []
var arr = arr || [];
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

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 = [];
}

如果你想检查对象是否已经是一个数组,为了避免在多Object.prototype.toString DOM 环境中工作时instanceof操作符的众所周知的问题,你可以使用Object.prototype.toString方法:

arr = Object.prototype.toString.call(arr) == "[object Array]" ? arr : [];
<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>   

If you are talking about a browser environment then all global variables are members of the window object. So to check:

if (window.somearray !== undefined) {
    somearray = [];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM