Javascript push() - 未定义的输出

时间:2017-08-19 18:13:01

标签: javascript undefined push

我目前尝试使用push()功能安全地保护数组中不同用户的数据 这是我目前的代码:

function data()
{

    var information = [];
    var imgs = '';
    var percentage;

    var imgs = 'ABC';
    var percentage = '1';

    information.push({ imgs: imgs, chance: percentage });

    var imgs = 'DEF';
    var percentage = '2';

    information.push({ imgs: imgs, chance: percentage });

    console.log(information);

    information.forEach(function(deposit)
    {
        var deposit=deposit.imgs;
        var chance=deposit.chance;

        console.log(deposit);
        console.log(chance);
    });


}

这是console.log(information)

的输出
[ { imgs: 'ABC', chance: '1' }, { imgs: 'DEF', chance: '2' } ]

这是information.forEach(function(deposit)

的输出
ABC
undefined
DEF
undefined

那就是我的问题。 如您所见,它输出的机会为undefined,但它应输出1和2。 任何人都知道它为什么这样做并知道如何解决它?

4 个答案:

答案 0 :(得分:6)

在下一行,您重新分配存款对象:

COUNT(...)

只需更改此变量名称即可。或者在存款前分配机会。

答案 1 :(得分:2)

您正在为存款变量分配一个值,该变量也是forEach函数中的参数。

因此,将deposit中的var deposit = deposit.imgs;变量更改为任何其他随机变量,并更新日志语句中的更改。 console.log(**deposit**);

希望这一点清楚,我希望它能解决你的问题。

答案 2 :(得分:0)

因为你声明了它是未定义的 var deposit=deposit.imgs; 存款这是另一个变量声明。 然后是下一行 var chance=deposit.chance;存款来自上方的var deposit,因此会产生 undefined 。只需将var deposit=deposit.imgs;更改为另一个变量,例如var images = deposit.imgs;

这将有效。

答案 3 :(得分:0)

forEach的{​​{1}}内有一个错误。基本上,您当前的代码会覆盖information的{​​{1}}(到字符串)。

您可以通过在currentValue内查找变量名称来解决此问题,如下所示。

forEach