我的java脚本数组没有't没有长度

My java script array doesn't have a length

本文关键字:数组 java 我的 脚本      更新时间:2023-09-26

我有以下代码:

//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
    var addData = {
        id : x[i].id,
        value : x[i].value
    };
    inputData[i] = addData;
    $('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}

我正试图将以前制作的表单中的表单数据传递给另一个javascript函数。在此之前,我曾尝试使其在同一个.js页面中工作,但当我尝试通过for循环输出inputData时,它显示为空白。我确定这是因为inputData.lengthundefined。我的印象是,将其声明为inputData = {};使其成为一个数组,因此具有默认的长度值。我怎样才能把它改成正确的长度?

编辑

一些评论者说var x = document.getElementById("newInventoryForm");应该返回null或一个节点,两者都没有长度属性。在上面的代码中添加这一行,就产生了这个输出。

我的x.length属性18序列号:456someDatafield:someInput

您已经将它声明为一个对象。

也许var inputData = [];会给你更好的结果。

{}是一个对象,而不是数组
您需要[]

此外,getElementById()不返回数组;你的整个代码毫无意义。