如何对for循环正在处理的数组进行延迟评估 [英] How to do lazy evaluation of an array being processed by a for loop

查看:118
本文介绍了如何对for循环正在处理的数组进行延迟评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

window.onload = function () {
    x = '';
    myArray =  [ {a:'a', b:'b'}, {a:'c', b:'d'}, {a:x, b:''} ];
    for (i = 0; i < myArray.length; i += 1) {
        x = myArray[i].a + myArray[i].b;
    }
    alert(x);  // alerts '';
}

以上是我正在尝试做的一个例子.基本上,我希望在第二个数组元素计算完x之后对其求值.我认为这被称为惰性评估,但不确定...我有点新.

Hi, the above is an example of what I'm trying to do. Basically, I would like for x to be evaluated after the 2nd array element computes it. I think this is called lazy evaluation, but not sure... I'm somewhat new.

我该如何处理循环中的数组并每次对x进行求值,以便当我进行第三次迭代时,x ='cd'并提示为'cd'?

How can I process my array in the loop and x be evaluated each time such that when I get to the third iteration, x = 'cd' and will alert as 'cd'?

推荐答案

我认为我已经在您的帮助下以及我在评论中提到的其他主题找到了答案.只需将x包裹在一个函数中,然后定义一个get函数即可应用于所有元素:

I think I figured out the answer with your help and the other thread I mentioned in the comment. Just need to wrap x in a function and then define a get function to apply to all elements:

window.onload = function () {
    function get(e) {return (typeof e === 'function') ? e () : e; }
    var x = '';
    myArray = [ {a:'a', b:'b'}, {a:'c', b:'d'}, {a:function() {return x; }, b:''} ];
    for (i = 0; i < myArray.length; i += 1) {
        x = get(myArray[i].a) + get(myArray[i].b);
    }
    alert(x); // alerts 'cd';
}

x可以是任何东西.例如,(x +'xyz')将警告'cdxyz'.这样一来,我就可以对要稍后(需要时)进行评估的任何变量进行正确评估(基于当时的状态).

x can be anything then. For example (x + 'xyz') will alert 'cdxyz'. So this way I can have any variable that I want evaluated later (when needed) be evaluated correctly (based on state at that point).

这就是我所需要的. :)

That's what I needed. :)

这篇关于如何对for循环正在处理的数组进行延迟评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆