如何访问[“ X”,“ X”,“ O”,“”,“ O”]

时间:2018-08-24 22:34:42

标签: javascript object prototype

function Type(name, effectivenessData) {
    this.name = name;
    this.effectivenessData = effectivenessData;
}

var types = [
    new Type("Fire", ["X", "X", "O", "", "O"]),
    new Type("Water", ["O", "X", "X", "", ""]),
    new Type("Grass", ["X", "O", "X", "", ""]),
    new Type("Electric", ["", "O", "X", "X", ""]),
    new Type("Ice", ["X", "X", "O", "", "X"])
];

var getTypes = function getTypeNames() {
    return types.map(t => t.name);
}

我的解决方案:大家好,我正在使用内部for循环访问effectiveData,但出现错误,提示长度未定义。能否请某人帮助我了解如何在此处访问数据。或者我在做什么错

for (var i =0; i < getTypes.length; i++) {
    console.log(getTypes[i].toString());

    for(var j=0; j< getTypes[i].effectivenessData; j++) {
console.log(getTypes[i].effectivenessData.[j]) // When I console log to check the data I get length undefined 
}
}

4 个答案:

答案 0 :(得分:1)

您可以使用类似的方法循环遍历:

function Type(name, effectivenessData) {
   this.name = name;
   this.effectivenessData = effectivenessData;
}

var types = [
    new Type("Fire", ["X", "X", "O", "", "O"]),
    new Type("Water", ["O", "X", "X", "", ""]),
    new Type("Grass", ["X", "O", "X", "", ""]),
    new Type("Electric", ["", "O", "X", "X", ""]),
   new Type("Ice", ["X", "X", "O", "", "X"])
];

for(var i = 0; i < types.length; i++){
   console.log(types[i].effectivenessData)
};

答案 1 :(得分:0)

您应该使用getTypes()[i]而不是getTypes[i],因为它是一个函数。

答案 2 :(得分:0)

似乎您正在尝试在一个循环中打印类型的name,而在另一循环中打印类型effectivenessData。您试图将getTypes当作数组索引,但这是不支持此类操作的函数。使用getTypes检索数组,然后在数组上调用forEach遍历其元素:

function Type(name, effectivenessData) {
    this.name = name;
    this.effectivenessData = effectivenessData;
}

var types = [
    new Type("Fire", ["X", "X", "O", "", "O"]),
    new Type("Water", ["O", "X", "X", "", ""]),
    new Type("Grass", ["X", "O", "X", "", ""]),
    new Type("Electric", ["", "O", "X", "X", ""]),
    new Type("Ice", ["X", "X", "O", "", "X"])
];

var getTypes = function () {
    return types.map(t => t.name);
};

getTypes().forEach(e => console.log(e));

types.forEach(e => console.log(e.effectivenessData));

// or, using a traditional loop:
for (let i = 0; i < types.length; i++) {
  console.log(types[i]);
}

如此处所示,getTypes是重命名(因为它确实返回类型 names )或删除(因为它似乎并没有为代码增加太多)的候选对象它站立着。)

答案 3 :(得分:0)

getTypes必须被调用,例如getTypes(),其返回值应存储在var中,以使迭代代码更简洁。