简体   繁体   中英

problems when receiving form array with only one element in javascript

I am receiving a html form. This works fine when 2 or more elements in array, but when only one element is received I get error users[t] is null in fireBug?

var users = form.elements["uname[]"];

for(t in users) {
  dataString += "User: "+users[t].value+"\n"
}

this solved it:

if( typeof users.value === 'string' ) {
   users = [ users ];
}

I know this is an old question but I stumbed across it while searching for something else. Anyway, I thought I'd provide another answer for anyone else who stumbled across this.

Rather than checking the type to see if it is an array or not and then optionally encasing the value in a new array, you can use Array.prototype.concat() .

Its syntax is

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

where any of those values can be either an array or a single value.

In your specific case, you can start with an empty array and concatenate your form input, which will work whether you get a single value or an array:

var users = [].concat(form.elements["uname[]"]);

or

users = [].concat(users);

You could check if the variable is a string and convert it to an array:

if( typeof users === 'string' ) {
    users = [ users ];
}

For iterating arrays for-in should be avoided, that statement is meant to enumerate object properties. You could try using a better loop, something like:

var userCount = users.length;
for (var i = 0; i < userCount; i++) {
      dataString += "User: "+users[i].value+"\n"
}

You could also base a test on the length. If the object is single it will return undefined for length.

var userCount = users.length; //Get user count
if ( userCount == undefined ) { //Returned undefined if not an array.
    users = [ users ]; //Convert to array
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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