mardi 15 décembre 2015

JavaScript: The `for loop` that works in an `if` statement does not work in a `ternary` statement? Why?

I've just picked up the concept of a ternary statement, and tried to use it in place of an if / else if / else statement that I'm familiar with. But the code seems to have a syntax error. What is a ternary statement unable to do that an if statement can do? I wonder if ternary statements are more appropriate for executing simple commands.


The 'bin' array is a collection of sub-arrays, consisting of items discarded from the 'inventory' array, courtesy of the splice and push methods.


var bin = [ ['Orichalcum'], ['Rapier', 'Panacea'], ['Bow'], ['Antidote', 'Cheese', 'Whip'],  
['Elixir', 'Herb'], ['Timbrel', 'Dagger', 'Boomerang'] ];


var message = (! bin.length) ?

     'No items have been removed.'

    : (bin.length === 1) ?

         bin[0].length + ' items have been removed.'

        : (
            for (var i = 1; i < bin.length; i++) {
                for (var j = 0; j < bin[i].length; j++) {
                    bin[0].push(bin[i][j]);
                }
            },

            bin[0].length + ' items have been removed.'
        );


alert(message);

Aucun commentaire:

Enregistrer un commentaire