我需要你在 JS 数组方面的帮助。 我有一个函数,我需要检查传入参数的数组是一维还是二维
假设:
function test(array){
if(array is single dimension{
console.log("Single dimension");
}else{
console.log("2Dimension");
并且应显示以下内容:
test([1,2,3]); // Should log "Single dimension"
test([[1,2,3],[1,2,3]]); // Should log "2Dimension"
任何帮助都会非常好!谢谢!
最佳答案
How to know if an array is single dimension or multiple dimension?
JavaScript 没有多维数组;它有数组的数组。这两件事之间有细微的差别。更重要的是,JavaScript 可以包含数组条目和其他不是数组的条目,使其只是部分“多维”。
如果您需要知道一个数组不包含任何数组(例如,是一维的),唯一的方法是检查其中的每个条目以查看该条目是否为数组:
if (theArray.every(entry => !Array.isArray(entry)) {
// One dimensional
} else {
// Has at least one entry that is an array
}
这是一个数组示例,其中只有一些 条目是数组,而其他条目不是:
const a = [1, 2, ["a", "b"], 3];
console.log(a.length); // 4, not 5
console.log(Array.isArray(a[0])); // false
console.log(Array.isArray(a[2])); // true
关于javascript - 如何知道数组是单维还是多维?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682252/