JS如何将整数从for循环推入数组

JS How to push integers from for loop into array

var period  = document.getElementById('period').value;
        var col = element.id.split('time')[1];
        var ValueArr=[];
        for(var x= 0;x < period; x++){
            var taskValue = document.getElementById('taskDone'+x).value;
            for(var p= 0;p < taskValue; p++){
                var ValueB = document.getElementById(col+"_"+taskValue).value;
                console.log(ValueB);
                ValueArr.push(ValueB);
                //var newValue = ValueArr.sort(function (a, b) {  return a - b;  });
            }
        }
        alert(newValue);

所以我在函数中有这个,我想将 ValueB 推入 ValueArr。 对于 ValueB 它将具有未指定的数字长度和未指定的数字但是当我尝试时我得到这个:https://imgur.com/a/Oz8Cy

你在 alert 中犯了错误。它应该是 alert(ValueArr); 而不是 alert(newValue); 。这就是您收到该错误 Reference error: newValue is not defined 的原因。您还需要 ValueArr 中的唯一元素,因此请使用此代码

var newValue = ValueArr.filter(function(itm, i, a) {
    return i == a.indexOf(itm);
});

固定码:

var period  = document.getElementById('period').value;
var col = element.id.split('time')[1];
var ValueArr=[];
for(var x= 0;x < period; x++){
    var taskValue = document.getElementById('taskDone'+x).value;
    for(var p= 0;p < taskValue; p++){
        var ValueB = document.getElementById(col+"_"+taskValue).value;
        console.log(ValueB);
        ValueArr.push(ValueB);
        var newValue = ValueArr.filter(function(itm, i, a) {
             return i == a.indexOf(itm);
        });
        //var newValue = ValueArr.sort(function (a, b) {  return a - b;  });
    }
}
alert(ValueArr);