简体   繁体   English

解析JavaScript中的数组数组

[英]Parse array of arrays in JavaScript

I need a function that would return a value from an array that may contain any number of arrays. 我需要一个函数,该函数将从可能包含任意数量数组的数组中返回一个值。 It should be called like getValueFromArray(array, [2, 4]) - this example should return 4th element of the 2d array of the passed array. 应该像getValueFromArray(array,[2,4])那样调用-此示例应返回所传递数组的2d数组的第4个元素。

Here is my code: 这是我的代码:

function getValueFromArray(arr, indexes){

var val,
    currentIndex = indexes[0];

    if(!arr[currentIndex] || arr[currentIndex] === '') return value = '';

    indexes.splice(0, 1);

    if(arr[currentIndex].length) 
        getValueFromArray(arr[currentIndex], indexes);
    else {
        val = arr[currentIndex];
        return val;
    }
 }


      var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]); // should return 3

      var x = getValueFromArray([[1,2,3,4], [1,2,3,4], [5,6,7,8]], [2, 3]); // should return 8

      var z = getValueFromArray(
                           [
                               [[1,2,3,4], [1,2,3,4], [1,2,3,4]],
                               [[1,2,3,4], [1,2,3,4]]
                           ], 
                           [0, 1, 2]
                          ); // should return 3

Such call should return 3, and if I debug the function, it actually returns the correct value but when I assign it to a variable, it returns undefined. 这样的调用应该返回3,并且如果我调试该函数,它实际上会返回正确的值,但是当我将其分配给变量时,它将返回未定义的值。 I guess it's because of the recursion, variable gets the value that is undefined during the first function call. 我猜这是因为递归,变量在第一个函数调用期间获取了未定义的值。 How can this be fixed? 如何解决?

Thank you! 谢谢!

You are not returning your recursive results. 您没有返回递归结果。

if(arr[currentIndex].length) 
    getValueFromArray(arr[currentIndex], indexes);

Should be: 应该:

if(arr[currentIndex].length) 
    return getValueFromArray(arr[currentIndex], indexes);

you missed one thing in your code(returning the result after if condition) try below given code:- 您错过了代码中的一件事(如果满足条件则返回结果)请尝试以下给定代码:

function getValueFromArray(arr, indexes){

    var val,
        currentIndex = indexes[0];

        if(!arr[currentIndex] || arr[currentIndex] === '') return value = '';

        indexes.splice(0, 1);

        if(arr[currentIndex].length) 
           return getValueFromArray(arr[currentIndex], indexes);
        else {
            val = arr[currentIndex];
            return val;
        }
     }
    var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]);
    console.log(y)

run it and see, now its showing the result into the variable. 运行它,然后看,现在将结果显示到变量中。

Your guess is correct. 你的猜测是正确的。 You simply forgot to return whatever the recursive call returns: 您只是忘了return递归调用返回的内容:

if(arr[currentIndex].length) 
    getValueFromArray(arr[currentIndex], indexes); // <---- here

That being said, I have to agree that you could easily do it more concisely (this will eventually destroy indexes , however): 话虽如此,我必须同意您可以轻松地更简洁地完成此操作(但这最终将破坏indexes ):

function getValueFromArray(arr, indexes){
  while(indexes.length) arr=arr[indexes.shift()]
  return arr
}

I think you need to add a return before getValueFromArray(arr[currentIndex], indexes); 我认为您需要在getValueFromArray(arr [currentIndex],indexs);之前添加一个返回值。
To make the final calculated value to recurse up the recursive method call stack as each recursed call returns. 为了使最终的计算值在每次递归调用返回时递归递归方法调用堆栈。

It's because if condition is not returning any value. 这是因为如果condition不返回任何值。 Try following code 尝试以下代码

function getValueFromArray(arr, indexes){

var val='',currentIndex = indexes[0];

    if(!arr[currentIndex] || arr[currentIndex] === '') return val;

    indexes.splice(0, 1);

    if(arr[currentIndex].length) {

       // Because if your function walks this way 
       // it does not meet any 'return' statement
       // till the end and returns nothing.
        return getValueFromArray(arr[currentIndex], indexes);
    }   
    else { 
        val = arr[currentIndex];
        return val;
    }
 }

Then console log you variable 然后控制台记录您的变量

var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]);
console.log(y)

I'll post my code too as I feel it provides a simpler solution to your problem. 我也将发布代码,因为我认为它为您的问题提供了更简单的解决方案。
There is no recursion involved, so it should run a bit faster in theory. 不涉及递归,因此理论上它应该运行得更快。

var arr = [
  [
    [
      [12, 5, 6],
      [ 6, 7, 8],
      [11, 0, 9]
    ],
    [
      [-1, 1, 8],
      [ 4, 5, 6]
    ]
  ],
  [
    [
        [7, 8, 9, 10]
    ]
  ]
];

function getValueFromArray(arr, indexes){
    var value = arr, i = 0, len = indexes.length, index = null;

    for (; i < len; i += 1) {
        index = indexes[i];
        // check if the current array contains an {index}-th record
        if ( index in value ) { 
            value = value[index];
        } else {
            // or throw an exception if you want
            return null;
        }
    }

    return value;
 }

getValueFromArray(arr, [0, 1, 1, 2]) // 6
function getValueFromArray(arr, indexes) {
    // exit if arr is not an array
    // exit if arr is empty
    // exit if indexes is not an array
    // exit if indexes is empty
    if (!Array.isArray(arr) || !arr.length || !Array.isArray(indexes) || !indexes.length) {
        return; // may throw exception or return other value
    }
    var currentIndex = indexes.shift();
    // exit if index is not in arr
    // exit if index is negative
    if (arr.length <= currentIndex || currentIndex < 0) {
        return; // may throw exception or return other value
    }
    return Array.isArray(arr[currentIndex]) ? getValueFromArray(arr[currentIndex], indexes) : arr[currentIndex];
}

You are overthinking this: 您对此太想了:

function getValueFromArray(arr, indexes){
    return arr[indexes[0]][indexes[1]];
}

EDIT for 1 to 3 dimensional array: 编辑1至3维数组:

function getValueFromArray(arr, indexes){
    if (indexes.length == 1) {
        return arr[indexes[0]];
    } else if (indexes.length == 2) {
        return arr[indexes[0][indexes[1]];
    } else if (indexes.length == 3) {
        return arr[indexes[0][indexes[1][indexes[2]];
    } else {
      // 4 dimensional arrays???
    }
}

Would you have more than 3 dimensional array? 您将拥有3维以上的阵列吗?

It would be best find a way to append indexes[i] but I can't think of a way at the moment and I don't think it's possible. 最好找到一种附加indexes[i]但我目前无法想到一种方法,而且我认为这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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