Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>var elements = [ { a:"a", b:"b"}, {a:"c", b:"d"}, {a:"e", b:"f"} ]; function getter(list, num) { var i, agg = { a: "", b: "" }; for (i = 0; i &lt;= num; i += 1) { agg.a += list[i].a; } return agg; } console.log(getter(elements, 0).a); // "a" console.log(getter(elements, 1).a); // "ac" console.log(getter(elements, 2).a); // "ace" </code></pre> <p>You can use a closure so you can't access the values, like:</p> <pre><code>var elements = [ { a:"a", b:"b"}, {a:"c", b:"d"}, {a:"e", b:"f"} ]; function make_getter(list) { return { get: function (num) { var i, agg = { a: "", b: "" }; for (i = 0; i &lt;= num; i += 1) { agg.a += list[i].a; } return agg; } }; } var getter = make_getter(elements); console.log(getter.get(0).a); // "a" console.log(getter.get(1).a); // "ac" console.log(getter.get(2).a); // "ace" </code></pre> <p>You can make different implementations of the aggregation function.</p> <p>With recursion:</p> <pre><code>var elements = [ { a:"a", b:"b"}, {a:"c", b:"d"}, {a:"e", b:"f"} ]; function getter(list, num) { var i, agg = list[num]; if (num &gt; 0) { agg.a = getter(list, num-1).a + agg.a; } return agg; } console.log(getter(elements, 0).a); // "a" console.log(getter(elements, 1).a); // "ac" console.log(getter(elements, 2).a); // "aace" &lt;-- note, elements are actually modified! console.log(getter(elements, 2).a); // "aaacaace" &lt;-- note, elements are actually modified! </code></pre> <hr> <p><strong>old answer</strong></p> <p>Since <code>x</code> is not an object it's value will be copied, rather than passed as a reference.</p> <p>If you change your code to:</p> <pre><code>var element = { a: '', b:'' }; myArray = [ {a:'a', b:'b'}, {a:'c', b:'d'}, element ]; for (i = 0; i &lt; myArray.length; i += 1) { element.a = myArray[i].a + myArray[i].b; } alert(el.a); // alerts 'cd'; </code></pre> <p>You will get <code>"cd"</code>.</p> <hr> <p>This is not called lazy evaluation by the way. It's just an aggregate or something.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload