在多维数组javascript中显示关联数组 [英] display an associative array in a multidimensional array javascript

查看:73
本文介绍了在多维数组javascript中显示关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用键用户名在多维数组中显示特定的关联数组.

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?

谢谢

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

推荐答案

无论您分配给它们多少键值,外部数组中的关联数组的长度均为0,因此您的内部循环永远不会运行.

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.

我很好奇为什么您仍然存在内循环.您应该只将zNamestorage[ctr].uName进行比较.

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

这篇关于在多维数组javascript中显示关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆