我在Chrome上运行以下代码时遇到此错误:未捕获的TypeError:undefined不是一个函数,就行了它作为注释编写的行。我已经在互联网上寻找类似的问题好几天但没有解决我的问题。这里是JS代码:
var myArr = [];
function loadExams() {
var token = getCookie("token");
var avgArr = [];
var avgZero = {
sAvg: 0,
sCfu: 0,
uDate: ""
};
dataIn = {
"action": "loadExams",
"token": token
};
ajaxPost(dataIn, "localPHP.php", function(dataOut) {
for (var i = 0; i < dataOut.length; i++) {
$("#editPick").append("<option value=" + dataOut[i]['n'] + ">" + dataOut[i]['sub'] + ": " + dataOut[i]['mark'] + " (" + dataOut[i]['date'] + ")" + "</option>");
if (i === 0) {
console.log(avgArr); //ok
console.log(dataOut[0]); //ok
console.log(avgZero); //ok
avgArr[0] = avg(dataOut[0], avgZero); //HERE ERROR >>>>>>>>>>>>>>> Uncaught TypeError: undefined is not a function <<<<<<<<<<<<<<<<<<<
} else {
avgArr[i] = avg(dataOut[i], avgArr[i - 1]); // same error here!
}
}
for (i = 0; i < myArr.length; i++) {
avg += myArr[i].mark * myArr[i].cfu;
cfu += myArr[i].cfu * 1;
}
i = dataOut.length - 1;
var avg = avgArr[i].sAvg / avgArr[i].sCfu;
document.getElementById('avg').innerHTML = Math.round(avg * 100) / 100;;
});
}
function avg(cur, prev) {
var avgTmp = {
sAvg: prev.sAvg,
sCfu: prev.sCfu,
uDate: cur.date
};
if (cur.type === "full") {
avgTmp.sAvg += cur.mark * cur.cfu;
avgTmp.sCfu += cur.cfu * 1;
} else {
for (var j = 0; j < myArr.length; j++) {
console.log(i + " " + cur.sub + " <> " + j + " " + myArr[j].sub);
if (myArr[j].sub === cur.sub) {
avg += (myArr[j].mark + cur.mark) / 2 * cur.cfu;
cfu += cur.cfu * 1;
myArr.splice(j, 1);
var flag = true;
break;
}
if (!flag) {
j = myArr.length;
var tmp = {};
tmp.sub = cur.sub;
tmp.mark = cur.mark;
tmp.cfu = cur.cfu;
myArr[j] = tmp;
}
}
}
console.log(avgTmp);
return avgTmp;
}
function ajaxPost(data, php, callback) {
ax = $.ajax({
type: "POST",
data: data,
url: php,
success: function (raw_data) {
f = $.parseJSON(raw_data);
callback(f);
},
error: function (xhr, desc, err) {
console.log("xhr: " + xhr + "\nAjax error. Details: " + desc + ", Error:" + err);
}
});
}
答案 0 :(得分:2)
我认为这是因为在函数loadExams
中你有一个陈述
var avg = avgArr[i].sAvg / avgArr[i].sCfu;
会影响你的函数定义(因为它在更大的内部范围内)。将变量重命名为其他东西(或函数)。
作为最佳做法,请在范围顶部定义变量,以便更容易跟踪。