Javascript push()-未定义的输出
目前,我尝试使用Javascript push()-未定义的输出,javascript,undefined,push,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 = 'D
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(信息)的输出:
这是信息的输出。forEach(功能(存款)
:
至少这是我的问题。
如您所见,它将机会输出为undefined
,但它应该输出1和2。
有人知道它为什么会这样做,并且知道我如何修复它吗?在下一行,您将重新分配您的存款对象:
var deposit=deposit.imgs;
只需更改此变量名称。或在存款之前分配机会。您正在为存款变量分配一个值,该值也是您的
forEach
函数中的参数
因此,将var-deposit=deposit.imgs;
中的deposit
变量更改为任何其他随机变量,并更新log语句中的更改。
console.log(**deposit**);
希望这是清楚的,我希望它能解决您的问题。因为您声明了
var-deposit=deposit.imgs;
存款这里是另一个变量声明。
然后是下一行
var-chance=deposit.chance;
此存款来自上面的var-deposit
,因此它将导致未定义。只需将var-deposit=deposit.imgs;
更改为另一个变量,如var-images=deposit.imgs;
这将起作用。在
信息的forEach
中有一个bug。基本上,您当前的代码覆盖了forEach
的当前值
(一个字符串)
您可以通过更改forEach
中变量的名称来解决此问题,如下所示
函数数据(){
var信息=[];
var-imgs='';
风险值百分比;
var imgs=‘ABC’;
风险值百分比='1';
信息推送({
imgs:imgs,
机会:百分比
});
var imgs=‘DEF’;
风险值百分比='2';
信息推送({
imgs:imgs,
机会:百分比
});
控制台日志(信息);
信息。forEach(功能(存款){
//更改变量的名称
var depositImgs=存款.imgs;
var存款变动=存款机会;
控制台日志(存款);
控制台日志(更改);
});
}
数据(< /代码>我很高兴它有帮助!如果你使用的是答案,你可以考虑接受这个答案:
ABC
undefined
DEF
undefined
var deposit=deposit.imgs;