display an associative array in a multidimensional array javascript

左心房为你撑大大i 提交于 2019-12-11 13:15:43

问题


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;
}


来源:https://stackoverflow.com/questions/50167028/display-an-associative-array-in-a-multidimensional-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!