1

基本上,我想输出这些吉他的评级,但我得到一个“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);
4

2 回答 2

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);
于 2013-06-19T08:35:22.080 回答
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这是您可以使用 () 调用的函数。

于 2013-06-19T16:42:18.877 回答