最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

adding multiple values to single array item in javascript - Stack Overflow

programmeradmin1浏览0评论

I am having trouble with output of an array, I think.

What I would like the output to look like is:

1. FirstName LastName DOB

but what I end up with is:

1. FirstName
2. LastName
3. DOB

Here is what I have so far but I am not seeing what I am doing wrong.

// global variable:
var tasks = []; 

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
    'use strict';

    // Get the task:
    var firstName = document.getElementById('firstName');
    var lastName = document.getElementById('lastName');
    var dob = document.getElementById('dob');

    // numerical value of dob
    var dateofBirth = new Date(dob.value);

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (firstName.value && lastName.value && dob.value) {

        // Add the item to the array:
        tasks.push(firstName.value, lastName.value, dateofBirth.toString());


        // Update the page:
        message = '<h2>Persons Entered</h2><ol>';
        for (var i = 0, count = tasks.length; i < count; i++) {
            message += '<li>' + tasks[i] + '</li>';
        }
        message += '</ol>';
        output.innerHTML = message;

    } // End of IF.

    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;

Thanks, I hope this helps you to help me.

I am having trouble with output of an array, I think.

What I would like the output to look like is:

1. FirstName LastName DOB

but what I end up with is:

1. FirstName
2. LastName
3. DOB

Here is what I have so far but I am not seeing what I am doing wrong.

// global variable:
var tasks = []; 

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
    'use strict';

    // Get the task:
    var firstName = document.getElementById('firstName');
    var lastName = document.getElementById('lastName');
    var dob = document.getElementById('dob');

    // numerical value of dob
    var dateofBirth = new Date(dob.value);

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (firstName.value && lastName.value && dob.value) {

        // Add the item to the array:
        tasks.push(firstName.value, lastName.value, dateofBirth.toString());


        // Update the page:
        message = '<h2>Persons Entered</h2><ol>';
        for (var i = 0, count = tasks.length; i < count; i++) {
            message += '<li>' + tasks[i] + '</li>';
        }
        message += '</ol>';
        output.innerHTML = message;

    } // End of IF.

    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;

Thanks, I hope this helps you to help me.

Share Improve this question edited Mar 18, 2020 at 16:14 mikemaccana 123k110 gold badges427 silver badges531 bronze badges asked Nov 4, 2012 at 14:20 punktilendpunktilend 731 gold badge3 silver badges7 bronze badges 2
  • 1 Because <li> are positioned vertically by default. You have to change your css about the <ol> <li> attribute with display: inline; list-style-type: none; if you want it to be horizontal without bullet point. Or, put them in the same <li> – Jeremy D Commented Nov 4, 2012 at 14:24
  • You should change your approach to begin with. This is a typical misuse of .innerHTML. Every time you add a new task, you're destroying the old ones and recreating them. – I Hate Lazy Commented Nov 4, 2012 at 14:28
Add a comment  | 

7 Answers 7

Reset to default 6
tasks.push({firstName: firstName.value, lastName: lastName.value, DOB: dateofBirth.toString()})

And then

tasks[0].firstName will output firstName.value
tasks[0].lastName will output lastName.value 

etc..

Edit

Using this, you can then construct your messasge like this :

for (var i = 0, count = tasks.length; i < count; i++) {
    message += '<li><span>' + tasks[i].firstName + '</span><span> ' 
    + tasks[i].lastName + '</span><span>' + tasks[i].DOB + '</span></li>';
}

Of course, the span tags are optionnal but this will allow you to apply a style to each part of the information in your css (width, padding, etc..) and you will always be able to easily select a property of a task by index

Your problem is that you're adding li elements to every element in your array, instead only add teh li once

    // Update the page:
    message = '<h2>Persons Entered</h2><ol><li>' + tasks.join(' ') + '</li></ol>';
    output.innerHTML = message;

Why do you put each element in its own <li>?

If you don't put it in different <li> but in a common one, everything will be fine

message = '<h2>Persons Entered</h2><ol><li>';

        for (var i = 0, count = tasks.length; i < count; i++) {
            message += tasks[i];
            message += " ";
        }
        message += '</li></ol>';
        output.innerHTML = message;

Use Span. you can use Array.join

output.innerHTML= '<h2>Persons Entered</h2><div><span>' + tasks.join("</span> <span>") +"</span>";

You want to add them as an array to the array, not as values to the array

What you have is this:

tasks.push(firstName.value, lastName.value, dateofBirth.toString());

what I think you want is this:

tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);

The answer above is the same, but with an object, not a array.

What you are doing is pushing multiple values into your array. What you want to be doing is to turn the different values into a single value and then push that value into your array. To get the exact output as you were requesting, you can turn these multiple values into one by concatenating them into a string:

Change this:

tasks.push(firstName.value, lastName.value, dateofBirth.toString());

Into this:

tasks.push(firstName.value + ' ' + lastName.value + ' ' + dateofBirth.toString());

However, this does mean you'll lose access to the individual values. If you want access to those, you could instead assemble them into an object:

tasks.push({"firstName" : firstName.value,
            "lastName" : lastName.value,
            "dateOfBirth" : dateofBirth.toString());

Its a little confusing what you are asking. If you simply want this:

1. FirstName LastName DOB

over this:

1. FirstName
2. LastName
3. DOB

Then your issue is not with the array but with how you are defining the loop code. Try this instead:

// Update the page:
message = '<h2>Persons Entered</h2><ol><li>';
for (var i = 0, count = tasks.length; i < count; i++) {
    message += tasks[i] + ' ';
}
message += '</li></ol>';

That way you are putting the array elements in a single list element, rather than across three of them.


EDIT - for Multi-dimensional array traversal

This is assuming that the array is defined this way (per Dan Steingart's answer):

tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);

We then can have the following:

// Update the page:
message = '<h2>Persons Entered</h2><ol>';

for (var i = 0, count = tasks.length; i < count; i++) {
    message += '<li> + tasks[i].toString().replace(',',' ') + '</li>';
}

message += '</ol>';

Here you are traversing each element of tasks when each element of tasks is also itself an array. The toString() on an inner array will display the values in a comma separated fashion, then the replace() function simply replaces the comma's with spaces.

发布评论

评论列表(0)

  1. 暂无评论