을 "정의의 속성을 읽을 수 없습니다". 몇 가지 대안과 잠재적 인 솔루션을 아무 소용이 시도했습니다. 나는이에 대한 답변을 위해 모든 것을 검색 한 적이 있지만이 같은 문제를 언급 다른 사람 발견하지 않았습니다
나는 다음과 같은 JSON 파일이 있습니다{
"subpatterns": {
"sub1": {
"selected": "V",
// other properties not important for this example
},
"sub2": {
"selected": "C",
// other properties not important for this example
},
"sub3": {
"selected": "N",
// other properties not important for this example
}
},
// other properties not important for this example
}
내가 그 데이터에 액세스하고 다음 코드를 사용하여 "서브 패턴"에서 각각의 키에 함수를 호출하고 있습니다 :
subPs.startup = function() {
function addStartData() {
for (var i = 1; i <= Object.keys(subPs.data.subpatterns).length + 1; i++) {
subPs.addRow(); // I want to add one more row than the amount of data I have (i.e. one blank row at the end), which is why the for loop is .length + 1
var selected = subPs.data.subpatterns["sub" + i].selected; // This is where it throws the error
console.log(selected); // But this works
if (selected !== undefined) {
subPs.selectSub(i, selected); // And this works, too
}
}
subPs.checkDupes();
}
var json = $.getJSON("../data/gen.json", function (json) {
subPs.data = json;
addStartData();
});
};
을 코드가 올바르게 실행됩니다. 기능 subPs.addRow()
및 subPs.selectSub()
모두 JSON/가변 selected
로부터의 정보를 포함하여 DOM에 올바른 데이터를 추가한다. 또한 console.log(selected)
을 호출하면 올바른 결과가 기록됩니다.
Uncaught TypeError: Cannot read property 'selected' of undefined
at addStartData (gen.js:28)
at Object.success (gen.js:41)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
어떻게 subPs.data.subpatterns["sub" + i]
정의 할 수있다, 그러나 또한 제대로 작동 : 그리고 아직 콘솔 오류가 말을 기록? 오류를 어떻게 해결할 수 있습니까?
동적 키 대신 ["sub1"]
을 사용했지만 이 아니고 오류가 발생했습니다. 이 배열에서 하나 이상의 오브젝트를 얻기 위해 노력하고 항상 undefined
될 것이기 때문에
왜 Object.keys (subPs.data.subpatterns)'주어진 "하위"처음에 + i''로 키를 재구성하는이 '실제 키 이름과 배열을 반환 그? 내가' "하위"+ i'를 사용하고 있는데 그 이유 @nnnnnn – nnnnnn
은 (내가 선택) subPs.selectSub'에서 호출 할 때 번호가 동일한 지 100 % 확인하는 것입니다 ', 그리고 나는 그들이 확실하게 원하기 때문에 다시 순서대로 액세스합니다. 그렇게 할 수있는 더 좋은 방법이 있습니까? – nai888