我对javascript和一般编码都很陌生,我不明白为什么这会导致无限循环:
let newTr = document.createElement('tr');
如果我把它拿出来,网页加载很好,但如果我不放进去,网页永远不会完全加载,我的浏览器占用了我50%的CPU。
这是我的其余代码:
// client-side js
// run by the browser each time your view template referencing it is loaded
console.log('hello world :o');
let arrPfcCases = [];
// define variables that reference elements on our page
const tablePfcCases = document.getElementById("tablePfcCases");
const formNewPfcCase = document.forms[0];
const caseTitle = formNewPfcCase.elements['caseTitle'];
const caseMOI = formNewPfcCase.elements['caseMOI'];
const caseInjuries = formNewPfcCase.elements['caseInjuries'];
// a helper function to call when our request for case is done
const getPfcCaseListener = function() {
// parse our response to convert to JSON
arrPfcCases = JSON.parse(this.responseText);
// iterate through every case and add it to our page
for (var i = 0; i = arrPfcCases.length-1;i++) {
appendNewCase(arrPfcCases[i]);
};
}
// request the dreams from our app's sqlite database
const pfcCaseRequest = new XMLHttpRequest();
pfcCaseRequest.onload = getPfcCaseListener;
pfcCaseRequest.open('get', '/getDreams');
pfcCaseRequest.send();
// a helper function that creates a list item for a given dream
const appendNewCase = function(pfcCase) {
if (pfcCase != null) {
tablePfcCases.insertRow();
let newTr = document.createElement('tr');
for (var i = 0; i = pfcCase.length - 1; i++) {
let newTd = document.createElement('td');
let newText = document.createTextNode(i.value);
console.log(i.value);
newTd.appendChild(newText);
newTr.appendChild(newTd);
}
tablePfcCases.appendChild(newTr);
}
}
// listen for the form to be submitted and add a new dream when it is
formNewPfcCase.onsubmit = function(event) {
// stop our form submission from refreshing the page
event.preventDefault();
let newPfcCase = [caseTitle, caseMOI, caseInjuries];
// get dream value and add it to the list
arrPfcCases.push(newPfcCase);
appendNewCase(newPfcCase);
// reset form
formNewPfcCase.reset;
};
谢谢!
第页。S.代码可能还有很多其他问题,在我弄清楚之前,我什么都做不了!
作为解释,在您的代码中
i = pfcCase.length - 1
将CCD_ 1的值分配给CCD_。循环的那个部分的语法应该是
在每次循环迭代之前要求值的表达式。若此表达式的计算结果为true,则执行语句。
对代码的评估毫无意义。
评估
i < pfCase.length
但是,在每次迭代之前,检查当前索引是否小于数组的长度,是否正常工作。
这里没有条件语句。在本语句中,您将pfcCase长度减1分配给I变量。
for (var i = 0; i = pfcCase.length - 1; i++) {
您必须将i变量与pfcCase的长度减去1进行比较。
这应该行得通。
for (var i = 0; i < pfcCase.length - 1; i++) {
注意到其他事情
这条线并没有达到你认为的效果。
let newText = document.createTextNode(i.value);
i只是一个索引,即一个数字。它没有value属性。
这就是你想要做的。
let newText = document.createTextNode(pfcCase[i].value);
我的偏好(每个(
我更喜欢使用数组forEach方法。它更干净,不容易出错。
pfcCase.forEach( function(val){
let newTd = document.createElement('td');
let newText = document.createTextNode(val.value);
console.log('The array element is. '. val.value, ' The value is. ', val.value);
newTd.appendChild(newText);
newTr.appendChild(newTd);
});