无法获得关联的数组值?

时间:2018-12-18 02:16:01

标签: javascript associative-array

不太确定这里发生了什么,因此请您澄清一下。

我创建了一个名为DBstats的对象,它包含基于以下内容的值:

team(string)==> {统计对象}

但是,当我尝试使用带有变量的键来获取对象时,我变得未定义,但是当我使用文字字符串值时,它就可以正常工作。

//populate the associative array, result is an object passed in as a parameter
for (var i = 0; i < result.length; i++)
{
    DBstats[result[i].Team] = result[i];
}

var Team1str = "team1";
console.log(DBstats); //prints everything in the associative array, confirming string => object
console.log(DBstats["team1"]); //prints out object
console.log(DBstats[Team1str]);  //prints undefined???

我不明白什么?

result array =
{
  team1: {team1.name, data... }
  team2: {team2.name,  data... }
  team3: {team3.name, data... } 
  team4: {team4.name,  data... }
  team5: {team5.name, data... } 
  team6: {team6.name,  data... }
  team7: {team7.name,  data... }
  team8: {team8.name,  data... }
  team9: {team9.name,  data... }

}

1 个答案:

答案 0 :(得分:0)

嘿,您的问题太多了,但是我喜欢这种问题(它们就像拼图)。

所以您可能想要这个:

private void initialLoad() {
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.container, AllGenreFragment.newInstance())
                .addToBackStack(null)
                .commit();
    }

    @Override public void OnItemClick() {
        // change `replace` to  `add` and add more `.addToBackStack(null)`
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.container, AllAnimeFragment.newInstance())
                .addToBackStack(null)
                .commit();
    }

  1. 您可能来自PHP世界。而且,不,JS中没有“关联数组”之类的术语。相反,它称为“对象”。
  2. 我已将非JS数组 const result = [ {name: 'team1', data: {}}, {name: 'team2', data: {}}, {name: 'team3', data: {}}, ] let DBstats = {} for (var i = 0; i < result.length; i++) { DBstats[result[i].name] = result[i]; } var Team1str = "team1"; console.log(DBstats); //prints everything in the associative array, confirming string => object console.log(DBstats["team1"]); //prints out object console.log(DBstats[Team1str]); //prints out object格式化为实际的JS语法。
  3. 一切正常(按“运行代码段”进行检查)!