试图从对象数组中访问javascript函数

时间:2013-06-19 08:22:51

标签: javascript

基本上,我想输出这些吉他的等级,但我得到一个“TypeError:taylorGuitar.guitarRating不是一个函数。这是代码:

    var taylorGuitar = [


{
    "model": "814ce",
    "stringsCount": 6,
    "pickup": true,
    "stringsTuning": ["E", "A", "D", "G", "B", "E"],
    "playabilityRating": 8,
    "soundRating": 10,
    "lookRating": 10,
    "woods": {
        "front": "Cedar",
        "back": "Rosewood",
        "fretboard": "Rosewood"
             }
},
{
    "model": "410ce",
    "stringsCount": 6,
    "pickup": true,
    "stringsTuning": ["E", "A", "D", "G", "B", "E"],
    "playabilityRating": 8,
    "soundRating": 9,
    "lookRating": 8,
    "woods": {
        "front": "Cedar",
        "back": "Rosewood",
        "fretboard": "Rosewood"
             }
},
{
        "guitarRating":  function(){
        totalScore = taylorGuitar.playabilityRating + taylorGuitar.soundRating + taylorGuitar.lookRating;
        return totalScore;
        }
}



];

var rating = taylorGuitar.guitarRating();
console.log(rating);

2 个答案:

答案 0 :(得分:1)

您的对象taylorGuitar是一个数组,因此您需要包含您想要的元素:

taylorGuitar[0].model;

您还将您的函数定义为该数组的一部分,这将使其难以访问,您的taylorGuitar对象需要有两个元素,您的数组和函数:

taylorGuitar.dataArray = [...]
taylorGuitar.guitarRating = function() {...}

然后你需要改变你的功能,以便循环遍历数组中的所有项目。

编辑:

我已经重写了你的代码,以便它现在可以工作并在关键点添加评论:

var taylorGuitar = {"data": [
{
  "model": "814ce",
  "stringsCount": 6,
  "pickup": true,
  "stringsTuning": ["E", "A", "D", "G", "B", "E"],
  "playabilityRating": 8,
  "soundRating": 10,
  "lookRating": 10,
  "woods": 
  {
     "front": "Cedar",
     "back": "Rosewood",
     "fretboard": "Rosewood"
  }
},
{
  "model": "410ce",
  "stringsCount": 6,
  "pickup": true,
  "stringsTuning": ["E", "A", "D", "G", "B", "E"],
  "playabilityRating": 8,
  "soundRating": 9,
  "lookRating": 8,
  "woods": 
  {
    "front": "Cedar",
    "back": "Rosewood",
    "fretboard": "Rosewood"
  }
}], //note array ends
"guitarRating":  function()
{
  totalScore = 0;
  //note you need to loop through the data
  for(i=0;i<this.data.length;i++)
  {
    d = this.data[i];
    totalScore += d.playabilityRating + d.soundRating + d.lookRating;
  }
  return totalScore;
}
};

var rating = taylorGuitar.guitarRating();
console.log(rating);

答案 1 :(得分:0)

taylorGuitar.guitarRating不是一个函数,也不是实际定义的。

taylorGuitar是一个数组,在你的情况下有三个对象:

[{/*omitted stuff for object 1 */}, {/*omitted stuff for object 2 */}, {/*omitted stuff for object 3 */}].

var object3 = taylorGuitar[2];
//object 3 now is the one:
{
    "guitarRating":  function(){
    totalScore = taylorGuitar.playabilityRating + taylorGuitar.soundRating + taylorGuitar.lookRating;
    return totalScore;
    }
}

最后一个对象是包含'guitarRating'

的对象

就像@elclanrs所说,taylorGuitar[2].guitarRating这是你可以使用()调用的函数。