-1

In the following example the j++ both acts as a variable and a function

 var j = 0;
 var arr = [];
 arr[j++] = "a1";
 arr[j++] = "a2";

 console.log(arr[0]);
 console.log(arr[1]);

is there a way to write this without using the ++ like:

function addx(i)
{
   return i+1;
}

var j=0;
arr[addx(j)] = "a1";
arr[addx(j)] = "a2";

the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable.

var j=0;
function addx(i)
{
   j = i+1;
   return j-1;
}
arr[addx(j)] = "a1";
arr[addx(j)] = "a2";

In Pascal you can declare the function like function addx(var i:integer) : integer; in which case the parameter would be the variable so having i := i+1; inside the function would update the calling variable too.

Ekim
  • 1,105
  • 11
  • 28
  • Function parameters are passed by value, they can't modify the caller's variables. – Barmar Jul 31 '14 at 05:59
  • `j++` is just shorthand for `j = j+1`. – Barmar Jul 31 '14 at 05:59
  • 1
    `++` does not act as a variable and a function. It acts as only a function. And no, as far as I know, you unfortunately have no way of passing variables by reference in javascript, unless you're working with objects. Also, your `addx` function is bad code, because it keeps changing a global variable that is passed in. This will get really hard to maintain and reason about. – Alxandr Jul 31 '14 at 06:00
  • 3
    @Barmar This is not true. `j++` is short for "take a copy of `j`, increment `j` by one, then return the copy". – Alxandr Jul 31 '14 at 06:01
  • @Alxandr Oh right, my answer is correct for `++j`. – Barmar Jul 31 '14 at 06:02
  • btw what is wrong with `arr.push()`? – Sirko Jul 31 '14 at 06:05
  • @Sirko Well, in this case that's probably what he wants. But there are cases where doing stuff like this is useful (though not normally with arrays, unless you need holes in them). – Alxandr Jul 31 '14 at 06:07

4 Answers4

2

This is the place where reference helps.

Like bellow

function addx(i)
{
   return i.val++;
}

var j={val:0};
arr[addx(j)] = "a1";
arr[addx(j)] = "a2";
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • thanks, this is a way I didnt know of. The code is part of a larger debugging library and changing the nature of the variables in the code that is being debugged could make the code not work later. I should have mentioned that, sorry. – Ekim Jul 31 '14 at 06:48
1

I assume from the constraint that this is some sort of homework problem? Otherwise it appears to be a completely artificial constraint.

One solution is to use a closure to maintain your variable state that supports a post increment function:

function NumberWrapper() {
    var value;  // initially undefined
    return {
        assign: function(n) {
            return value = n;
        },
        postincrement: function() {
            var result = ++value;
            ...
            return result;  // to emulate post-increment semantics
        }
    };
};

var i = new NumberWrapper();
var arr = [];
arr[i.next()] = "a1";
arr[i.next()] = "a2";

The NumberWrapper object maintains its own state, and the only functionality it exposes is incrementing itself and returning that value (in one step).

EDIT ok, interesting use case, hmm - the wrapper above could be extended to provide a clean implementation for other numeric operations:

 return {
     postincrement: ...
     preincrement: function() { return ++value; }
     plusequals: function(n) { value += n; return value; }
     minusequals: function(n) { value -= n; return value; }
     etc...
 };
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    It is for a debugging tool, that parse javascript code and change it so variables can be watched in realtime on another page. Assignments using = += -= are easy to replace with a function that both logs the value and sets it, ++ is normally ok to replace with i=function(..), but not when it is used as a parameter in an array or function call (using ++ as a parameter seems risky to me but people still do so I want to find a way to make it work on that) – Ekim Jul 31 '14 at 06:22
  • @Ekim interesting - if you happened to have a class that encapsulates variable state as above then adding a post-increment function would not be that hard. The only bit you have to remember is that the `x++` operator evaluates to the value `x` had _before_ it was incremented. – Alnitak Jul 31 '14 at 06:30
  • also, you may receive up votes instead of down votes for the question if you had actually explained this in the question, otherwise it looks like a rather odd (and artificial) question. – Alnitak Jul 31 '14 at 06:33
  • I had originally added it but then removed it as it wasn't contributing to the question itself. :) – Ekim Jul 31 '14 at 06:45
  • @Ekim ok, but anything that gives a rationale for a question that without it looks kinda pointless (or artificial) is useful here. It can also result in more useful or thoughtful answers. – Alnitak Jul 31 '14 at 08:36
0

You can do this:

var oldj;
var j = 0;
var arr = [];
arr[oldj = j, j = addx(j), oldj] = "a1";
arr[oldj = j, j = addx(j), oldj] = "a2";

This makes use of the rarely-used comma operator to combine a sequence of expressions into a single expression. We save the old value of j, update j with the result of addx, then use the old value as the index in the array to assign to.

Unfortunately, Javascript doesn't have macros, so there's no way to abbreviate that verbose code.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • this works as I need it, both in arrays and as function parameters, testfunc( (oldj = j, j = addx(j), oldj), "hi") instead of testfunc( j++, "hi") – Ekim Jul 31 '14 at 06:28
  • That's right, you can use it anywhere that an expression is allowed. As you noticed, you need an extra set of parentheses in function arguments, because otherwise the comma would be treated as a parameter delimiter instead of the comma operator. – Barmar Jul 31 '14 at 06:30
0

You can add subsequent elements to an array with the push method:

arr.push("a1");
arr.push("a2");

This makes j unnecessary and also avoids gaps in the array indices.

chm-software.com
  • 351
  • 2
  • 10