开发者

javascript - loop multidimesntional array

开发者 https://www.devze.com 2022-12-13 17:13 出处:网络
I am sure this is really simple, I used to have a function for checking the conten开发者_运维知识库ts of an array. Now Id like to modify it to check a two dimensional array.

I am sure this is really simple, I used to have a function for checking the conten开发者_运维知识库ts of an array. Now Id like to modify it to check a two dimensional array.

function ChkArray(Str, Val){

for (var i=0;i<Str.length;i++){
        if (Str[i] == Val) {return i;}
    }
return -1;
}

My new attempt:

function ChkArray2(Str, Val){

for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[ii].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
return -1;
}


Close, in your inner loop, you want to check the length of the current item in the outer loop:

function ChkArray2(Str, Val){

    for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[i].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
    return -1;
}

that should work


If you're asking about better ways to tackle the problem, I would perhaps think about writing a function which can work with any number of dimensions in the array. In your example, the return value is the index of the top level array, but to make it generic, you would have to return the full "path" to the found element, and let the calling code decide what information it wants:

    function multiFind(arr, val) {  // please don't name an array "str"!
    for (var i = 0, l = arr.length; i < l; ++i) {
        if (arr[i] === val) {
            return [i];
        } else if (is_array(arr[i])) {
            var ret = multiFind(arr[i], val);
            if (ret !== false) {
                ret.unshift(i);
                return ret;
            }

        }
    }
    return false;
}

// this function by Doug Crockford
var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

var inp = ["a","b",["c", ["d", "e", ["f", "g"], "h"]]];

multiFind(inp, "a"); // [0]
multiFind(inp, "b"); // [1]
multiFind(inp, "c"); // [2, 0]
multiFind(inp, "f"); // [2, 1, 2, 0]
multiFind(inp, "h"); // [2, 1, 3]
multiFind(inp, "x"); // false


I suggest using javascript foreach.

function ChkArray2(Str, Val){    
    for (var i in Str){
        for (var ii in Str[i]){
            if (Str[i][ii] == Val){
                return i;
            }
        }
    }
    return -1;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消