简体   繁体   English

我的Java脚本数组没有长度

[英]My java script array doesn't have a length

I have the following code: 我有以下代码:

//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/>");
}

I'm attempting to pass the form data from a previously made form to another javascript function. 我正在尝试将表单数据从先前制作的表单传递到另一个javascript函数。 Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. 在此之前,我试图使其全部在同一.js页面中工作,但是当我尝试通过for循环输出inputData ,它显示为空白。 I determined this is because inputData.length is undefined . 我确定这是因为inputData.lengthundefined I was under the impression that declaring it as inputData = {}; 我的印象是,将其声明为inputData = {}; made it an array and thus had a default length value. 将其设置为数组,因此具有默认长度值。 How can I change this to have the correct length? 我该如何更改为正确的长度?

Edit 编辑

Several commenters have said that var x = document.getElementById("newInventoryForm"); 一些评论者说var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. 应该返回null或节点,两者都不具有length属性。 Adding the line in the code above, has produced this output. 在上面的代码中添加该行,就产生了此输出。

My x.length property 18 serialNumber : 456 someDatafield : someInput 我的x.length属性18 serialNumber:456 someDatafield:someInput

You've declared it as an object. 您已将其声明为对象。

Perhaps var inputData = []; 也许var inputData = []; will give you better results. 会给你更好的结果。

{} is an object, not an array. {}是一个对象,而不是数组。
You want [] . 您想要[]

Also, getElementById() does not return an array; 同样, getElementById()不返回数组; your entire code makes no sense. 您的整个代码毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM