简体   繁体   English

“ JavaScript对象可以通过字符串索引”是什么意思?

[英]What does it mean by “JavaScript objects can be indexed by strings”?

var people = new Array();
function People (name, location, age){
    this.name = name;
    this.location = location;
    this.age = age;
}

I have two other functions to generate the people and load them into a table. 我还有另外两个函数来生成人员并将它们加载到表中。

function generatePeople(){}
function loadPeopleIntoTable(){}

I need to basically go through the list of people, take their names and then show the most common first names that appear in that table. 我基本上需要仔细检查一下人员列表,记下他们的名字,然后显示该表中最常见的名字。 That function is simply called commonFirstName(). 该函数简称为commonFirstName()。

function commonFirstName(){}

The hint given is "JavaScript objects can be indexed by strings" but I don't understand that 100%. 给出的提示是“ JavaScript对象可以通过字符串索引”,但我不明白那是100%。 I have already written the code for going through the array and finding the common first name. 我已经编写了遍历数组并查找通用名字的代码。 But I can't call in the peoples array to go through that list - I can only get it to work with a manual created array in commonFirstName(). 但是我无法调用peoples数组来遍历该列表-我只能使其与commonFirstName()中的手动创建的数组一起使用。 Why is that? 这是为什么?

I can provide some further clarification if needed. 如果需要,我可以提供一些进一步的说明。


function commonFirstName(){ 
       alert(people[1]); 
       //Rest of code that does the occurrences/name here 
 }

The output for this is simply [object Object]. 此输出仅是[object Object]。

On the other hand: 另一方面:

function commonFirstName(){
tempArray = ['John Smith', 'Jane Smith', 'John Black'];
//Run through algorithm for finding common name. 
}

Gives an alert output of "Common Name: John. Occurs 2 times" 给出警报输出“公用名:John。出现两次”

I had thought if I simply passed the array people through the function such as: 我曾想过,如果我只是通过以下函数传递数组人:

function commonFirstName(people){
alert(people[1]);
}

Should give me something, anything. 应该给我一些东西。 I'm not expecting just the first name at this point but at least the full name, location and age of element 1 or one of those. 在这一点上,我不期望只有名字,而元素1或其中一个的至少全名,位置和年龄也不会。 It just doesn't run at all, as though the array doesn't exist or is simply empty. 它只是根本不运行,就好像该数组不存在或只是空的。

This is my code for everything I have: 这是我拥有的所有内容的代码:

    var PEOPLECOUNT = 100;
    var people = new Array();

    function People(name, location, age) {
      this.name = name;
      this.location = location;
      this.age = age;
    }

    function initPage() {
      generateTableRows();
      generatePeople();
    }

    function generateTableRows() {
      var table = document.getElementById("ageTable");
      var tableBody = table.getElementsByTagName("tbody")[0];

      for (var i = 0; i < PEOPLECOUNT; i++) {
        var newRow = document.createElement("tr");

        newRow.setAttribute("id", "ageRow" + i.toString(10));

        var td1 = document.createElement("td");
        var td2 = document.createElement("td");
        var td3 = document.createElement("td");

        td1.setAttribute("class", "dataCell");
        td2.setAttribute("class", "dataCell");
        td3.setAttribute("class", "dataCell");

        newRow.appendChild(td1);
        newRow.appendChild(td2);
        newRow.appendChild(td3);
        tableBody.appendChild(newRow);
      }
    }

    function generatePeople() {
      var firstNames = ["Jack", "Will", "Josh", "Tom", "Sam", "Chloe", "Emily", "Sophie", "Lily", "Olivia"];
      var surnames = ["Smith", "Jones", "Brown", "Taylor", "Johnson", "White"];
      var locationNames = ["Canyonville", "Hailsmere", "Northpath", "Gracemont", "Gainsburgh", "Heathersmith"];

      for (var i = 0; i < PEOPLECOUNT; i++) {
        var name = firstNames[randInt(firstNames.length - 1)] + " " + surnames[randInt(surnames.length - 1)];
        var location = location[randInt(locationNames.length - 1)];
        var age = randInt(100);
        var currentPeople = new People(name, location, age);

        people.push(currentPeople);
      }

      loadPeopleIntoTable();
    }

    function loadPeopleIntoTable() {
      for (var i = 0; i < PEOPLECOUNT; i++) {
        var people = people[i];
        var peopleRow = document.getElementById("ageRow" + i.toString(10));
        var cells = peopleRow.getElementsByTagName("td");

        for (var j = 0; j < cells.length; j++) {
          if (cells[j].hasChildNodes()) {
            cells[j].removeChild(cells[j].childNodes[0]);
          }
        }

        cells[0].appendChild(document.createTextNode(people.name));
        cells[1].appendChild(document.createTextNode(people.location));
        cells[2].appendChild(document.createTextNode(people.age.toString(10)));
      }
    }

function randInt(maxVal) {
                return Math.floor(Math.random() * (maxVal + 1));
            }

    function commonFirstName() {

      var tempArray = [];
      var fName;
      var array = ['John Smith', 'Jane Smith', 'John Black'];
      for (i = 0; i < array.length; i++) {
        fName = array[i].split(' ').slice(0, -1).join(' ');
        tempArray.push(fName);
      }

      var mostCommon;
      var occurences = 0;
      for (j = 0; j < tempArray.length; j++) {
        var tempName = tempArray[j];
        var tempCount = 0;
        for (k = 0; k < tempArray.length; k++) {
          if (tempArray[k] == tempName) {
            tempCount++;
          }
          if (tempCount > occurences) {
            mostCommon = tempName;
            occurences = tempCount;
          }
        }
      }
      alert(mostCommon + " : " + occurences);
    }

Now this works with the array fullNames that is in the function but not for the array of people, which consists of People objects with name, location and age (as shown at the start). 现在,它可以与函数中的fullNames数组一起使用,但不适用于人员数组,该数组由具有名称,位置和年龄的People对象组成(如开头所示)。 I just need that array passed through so I can split the elements -_- 我只需要通过该数组,以便可以拆分元素-_-

"JavaScript objects can be indexed by strings" means that an object in JavaScript it's like a hash table. “ JavaScript对象可以由字符串索引”意味着JavaScript中的对象就像哈希表一样。 The method/field name it's just a String key in that table object.anyName can be written as object['anyName'] . 它只是在表中的字符串键的方法/字段名object.anyName可以写为object['anyName']

For you exercise you can use that to create a counter of the common used names. 在练习时,您可以使用它来创建一个常用名称的计数器。

Since it's an exercise I'll not give you the full answer ;) just the idea: 由于这是一种练习,因此我不会为您提供完整的答案;)仅是这样的想法:

  • For each item in the array, take the person name. 对于数组中的每个项目,请输入人名。
  • Use the person name as key of a "table", if the name is already there sum one to the counter. 如果此名称已经存在,则使用人员名称作为“表”的键。
  • In the end you'll have an pairs of name/occurrences 最后,您将获得一对名称/出现

If you are very lazy about the exercise... look at the source code of lodash countBy function ( https://github.com/lodash/lodash/blob/4.13.1/lodash.js#L8373 ), it does what you need. 如果您对练习非常懒...请查看lodash countBy函数的源代码( https://github.com/lodash/lodash/blob/4.13.1/lodash.js#L8373 ),它可以完成您的工作需要。

Regarding your edit: passing the array as an argument works fine, you don't need to have the array inside the function: 关于您的编辑:将数组作为参数传递可以正常工作,您无需在函数内部包含数组:

var fullNames = ['John Smith', 'Jane Smith', 'John Black'];

function commonFirstName(array) {                

            var tempArray = [];
            var fName;
            for (i=0; i < array.length; i++){
                fName = array[i].split(' ').slice(0, -1).join(' ');
                tempArray.push(fName);
            }

            var mostCommon;
            var occurences = 0;
            for (j=0; j < tempArray.length; j++){
                var tempName = tempArray[j];
                var tempCount = 0;
                for (k=0; k < tempArray.length; k++){
                    if (tempArray[k] == tempName){
                        tempCount++;
                    }
                    if (tempCount > occurences){
                        mostCommon = tempName;
                        occurences = tempCount;
                    }
                }
            }
            alert(mostCommon + " : " + occurences);
        }

 commonFirstName(fullNames);

Check the fiddle: https://jsfiddle.net/d2m105pb/ 检查小提琴: https : //jsfiddle.net/d2m105pb/

All good I have figured out what was wrong. 一切都很好,我弄清楚了什么地方出了问题。 Because of the objects that make up the array People you will need to call the specific variable inside the object - people[i].name for example. 由于对象组成了数组People,因此您需要在对象内部调用特定变量-例如people [i] .name。 Instead of people[i] just by itself. 而不是仅仅靠人[i]。

Thank you for all the input :) 谢谢您的所有投入:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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