【问题标题】:Javascript push() - undefined outputJavascript push() - 未定义的输出
【发布时间】:2017-08-19 18:13:01
【问题描述】:

我目前尝试使用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。 任何人都知道它为什么这样做并且知道我该如何解决它?

【问题讨论】:

    标签: javascript undefined push


    【解决方案1】:

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

    var deposit=deposit.imgs;
    

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

    【讨论】:

    • 我很高兴它有帮助!如果它是您使用的答案,您可以考虑接受它:)
    【解决方案2】:

    您正在为 deposit 变量赋值,这也是您的 forEach 函数中的参数。

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

    希望这很清楚,我希望它能解决您的问题。

    【讨论】:

      【解决方案3】:

      它是未定义的,因为你声明了 var deposit=deposit.imgs; deposit 这里是另一个变量声明。 然后下一行 var chance=deposit.chance; 这个 deposit 是从上面的 var deposit 得到的,所以它会导致 undefined。只需将var deposit=deposit.imgs; 更改为另一个变量,例如var images = deposit.imgs;

      这会起作用。

      【讨论】:

        【解决方案4】:

        informationforEach 内部有一个错误。基本上,您当前的代码会覆盖 forEachcurrentValue(到字符串)。

        您可以通过更改forEach 中的变量名称来解决此问题,如下所示。

        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) {
            // change name of variables
            var depositImgs = deposit.imgs;
            var depositChange = deposit.chance;
        
            console.log(depositImgs);
            console.log(depositChange);
        
        
          });
        }
        data();

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-08
          • 2016-09-20
          • 1970-01-01
          • 2021-12-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多