简体   繁体   中英

JS Array - convert string to key

Edit : thanks, I misused the eval function, now this works fine that way : eval('foo'+bar), instated of foo[eval(bar)] or eval(foo[bar]). This was very simple finally...


For some reasons, I have to convert a string to a valid index to access elements in a complex multidimensionnal array. For example, let's say I have this :

var foo = [
    [1,2,3],
    [
        4,
        [5,6]
    ]
];

var bar  =  [
    1: "[0][0]", 
    2: "[0][1]", 
    3: "[0][2]", 
    4: "[1][0]", 
    5: "[1][1][0]", 
    6: "[1][1][1]"
];

var selectVal5 = foo[bar[5]];

I tried few eval() tricks, but it doesn't seem to work. So, any idea to solve this ?

I tried a simple eval and it works.

var foo = [
    ['val1','val2'],
    ['val3']
];
var bar  = "[1][0]";
foo[eval(bar)].toString(); //added to String so that the brackets can be removed

It works using eval and String :

<input type="button" value="test" />
<div id="result"></div>  

This is the script:

$('input[type=button]').click( function() {
    var foo = [
    ['val1','val2'],
    ['val3']
    ];
    var bar  = "[1][0]";
    var selectVal3 = String(foo[eval(bar)]);

    $("#result").append(selectVal3);
});

http://jsfiddle.net/pUeue/

If you know the name of multidimensional array, you can use

eval('foo' + bar). 

This will return right the content without any brackets. If no, you may use regex to extract dimensions from string, like

bar.match(/[0-9]+/g).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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