Javascript 如何检查数组是否存在并以其他方式创建它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1961528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:07:19  来源:igfitidea点击:

How to check if an array exists and create it otherwise?

javascriptarrays

提问by ajsie

How do I check if a specific array exists, and if not it will be created?

如何检查特定数组是否存在,如果不存在,将创建它?

回答by Rich

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

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

x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []

回答by Brian Campbell

var arr = arr || [];

回答by Gumbo

You can use the typeofoperatorto test for undefinedand the instanceofoperatorto test if it's an instance of Array:

您可以使用typeof运算符来测试undefined并使用instanceof运算符来测试它是否是Array的实例:

if (typeof arr == "undefined" || !(arr instanceof Array)) {
    var arr = [];
}

回答by CMS

If you want to check if the object is already an Array, to avoid the well known issuesof the instanceofoperator when working in multi-framed DOM environments, you could use the Object.prototype.toStringmethod:

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

arr = Object.prototype.toString.call(arr) == "[object Array]" ? arr : [];

回答by M RAHMAN

<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>   

回答by slebetman

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

如果您在谈论浏览器环境,那么所有全局变量都是 window 对象的成员。所以要检查:

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