[英]Differentiate between array of arrays and array of values
I have two arrays: 我有两个数组:
var firstarray = [123, 13, 34, 12, 63, 63];
var secondarray = [[10,20,10], [122, 123, 53], [542, 234, 12, 331]];
I need to have a function that works something like this: 我需要有一个类似这样的功能:
function checkArray(array){
//if array contains multiple arrays, return true
//if the array contains only values, return false
}
The number of arrays inside secondarray
always varies. secondarray
内部的数组数量始终是变化的。
Hint: Loop on the first array and determine if one of the object you're reading is an array. 提示:在第一个数组上循环并确定您正在读取的对象之一是否是数组。
Here is a function that could help you : 这是一个可以帮助您的功能:
function is_array(input){
return typeof(input)=='object'&&(input instanceof Array);
}
In modern Javascript: 在现代Javascript中:
myAry.every(Array.isArray) // returns true if all elements of myAry are arrays
References (and replacements for older browsers): 参考(和旧浏览器的替代品):
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
The main problem to this is that in JavaScript typeof anArrayVariable
returns object
as does typeof aRealObject
- so there's no easy way to distinguish them. 这个主要的问题是,在JavaScript typeof anArrayVariable
返回object
一样typeof aRealObject
-所以有没有简单的方法来区分它们。
jQuery fixes this to some extent with a method $.isArray()
which correctly returns true for an array and false for an object, a number, a string or a boolean. jQuery使用$.isArray()
方法在某种程度上修复了此问题,该方法可以为数组正确返回true,而对于对象,数字,字符串或布尔值则返回false。
So, using jQuery this becomes as easy as: 因此,使用jQuery变得很容易:
function checkArray(array){
//if array contains multiple arrays, return true
//if the array contains only values, return false
for(var i=0;i<array.length;i++){
if($.isArray(array[i]))
return true;
}
return false;
}
I suggest you could take a look at the source for that method in jQuery and implement this same idea in vanilla javascript. 我建议您可以看看jQuery中该方法的源代码,并在普通javascript中实现相同的想法。
Check the type of the first element in the array: 检查数组中第一个元素的类型:
function checkArray(list) {
return typeof(list[0]) == "object";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.