简体   繁体   中英

JavaScript equivalent of PHP $array[$i][]

I have a problem with the creation of a multidimensional array in JavaScript.

The PHP code looks like this:

<?php
$matches = array(1, 2, 3, 4, 4, 4, 6, 6, 2, 3);

foreach($matches as $match) {

     $levels[$match][] = $match;
}

print_r($levels);
?>

print_r of $levels:

levels[1][0] = 1
levels[2][0] = 2
levels[3][0] = 3
levels[4][0] = 4
levels[4][1] = 4
levels[4][2] = 4
levels[6][0] = 6
levels[6][1] = 6
levels[2][1] = 2
levels[3][1] = 3

I have a problem with the creation the same array in JavaScript.

<script>
var levels = [];

$([1, 2, 3, 4, 4, 4, 6, 6, 2, 3]).each(function(key, value) {

     levels[value][] = value;
});
</script>

Can someone help me create the same array in JavaScript?

JavaScript doesn't magically create an array if there is none. You have to create it yourself. So it would be something like

$([1, 2, 3, 4, 4, 4, 6, 6, 2, 3]).each(function(key, value) {
    if (levels[value] == null) {
        levels[value] = [];
    }
    levels[value].push(value);
});

Learn more about arrays .

Felix's answer is good and readable, I just want to introduce you to a couple of useful idioms.

Unlike php, javascript || (boolean OR) operator, despite its name, doesn't return boolean, but rather the first non-falsy operand. So when you write

a = thing || otherThing

the result will be otherThing if thing is falsy (= null, undefined, 0, empty string ). Therefore checks like this

if(!foo)
   foo = bar

can be written more concisely as

foo = foo || bar

If foo is truthy, it just assigns foo to foo (a no-op), otherwise, foo becomes bar .

Applied to your problem, this will look like this:

levels[value] = levels[value] || [];
levels[value].push(value);

If you want to shorten this even more, replace push with concat :

levels[value] = (levels[value] || []).concat(value);

This is not necessarily more readable or efficient, just something worth knowing about.

var levels = [];
var orgArray = [1, 2, 3, 4, 4, 5, 6, 2];
for (var i = 0; i < orgArray.length; i++) {
    var value = orgArray[i];
    if (levels[value] === undefined)
        levels[value] = []
    levels[value].push(value);
}
//Print
for (var j = 0; j < levels.length; j++)
    if (levels[j])
        for (var k = 0; k < levels[j].length; k++)
            console.log("levels[" + j + "][" + k + "] = " + levels[j][k]);

It's a bit overkill but you will get the point I think. Don't forget to check if your elements exists

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