display an associative array in a multidimensional

2019-08-15 03:38发布

问题:

I am trying to display a specific associative array in a multidimensional array using the key username.

so if a user inputs the username, the only value that will be displayed in the console would be the objects of the associative array "username" that is inputted by the user if it is stored.

but every time that I am inputting a value the console does not display anything, what seems to be the problem of my code?

Thankyou

var storage = [];

function viewUserArray()
{   
    var zName = document.getElementById('checkArray').value;

    for (var ctr = 0; ctr < storage.length; ctr++)
    {
        for (var ctr2 = 0; ctr2 <= storage[ctr].length; ctr2++)
        {
            if (storage[ctr][ctr2] === zName)
            {
                console.log(storage[ctr][ctr2])
            }
            else
            {
                alert ("Username not Found.")
                return false;
            }
        }
    }
}

function array()
{
    var uName = document.getElementById('username').value;
    var fName = document.getElementById('fullName').value;
    var elmail = document.getElementById('email').value;
    var pword = document.getElementById('password').value;
    var b_day = getAge();
    var g_nder = document.getElementById('gender').value;

    var person = [];

    person[uName] = {
        "Username" : uName,
        "Full Name" : fName,
        "Email" : elmail,
        "Password" : pword,
        "Age" :  b_day,
        "Gender" : g_nder                   
    };
    storage.push(person);               
}

回答1:

The associative arrays within the outer array have a length of 0 no matter how many key values you assign to them, so your inner loop never runs.

I'm curious why you're inner loop exists anyway. You should just be comparing zName to storage[ctr].uName.

Something like this would make more sense to me:

function viewUserArray() {   
  var zName = document.getElementById('checkArray').value;

  for (var ctr = 0; ctr < storage.length; ctr++) {
    if (storage[ctr].uName === zName) {
      console.log(storage[ctr]);
      return true;
    }
  }

  alert ("Username not Found.");
  return false;
}