提问者:小点点

如何在javascript中将选定的单选按钮选项推送到数组


我正在尝试建立一个测试,其中显示一个问题的每一张幻灯片动态。 我希望在单击下一个/上一个问题时保留所选答案。 我尝试了下面的代码。 当试图从数组中获取值时,这是返回的NaN.即使我在幻灯片中前进和后退,数组的长度也在增加。 谁能帮帮忙-

function choose() {
    console.log("selection -"+$('input[name="answer"]:checked').val())
    selections[questionCounter] =+ $('input[name="answer"]:checked').val();
    console.log("selections - "+selections[questionCounter])  
  }

完整代码here


共1个答案

匿名用户

而不是使用

selections[questionCounter] =+ $('input[type="radio"]:checked').val();

您需要使用

selections[questionCounter] = $('input[type="radio"]:checked').val();

因为您已经作为[]启动了选择selections[questionCounter]=$('input[type=“radio”]:checked').val();将为您创建相应的数组索引。 当您在值前面使用+时,该值试图将$('input[type=“radio”]:checked').val()强制转换为数字。 您正在尝试将字符串类型强制转换为数字。 这就是您获得NaN的原因。

null

console.log(+"a");