![](/img/trans.png)
[英]Is it possible to fix unused variable in function for jslint and jshint?
[英]Undefined function uncaught by JSHint and JSLint
最近,我一直在使用JavaScript為我的網站開發Cookie系統。 現在,當我將它們放在一起時,它們拒絕在Chrome的JavaScript控制台中運行。
它說TypeError: undefined is not a function
盡管一切似乎都已正確定義。
我已經通過JSLint和JSHint運行了它們,但它們沒有發現任何錯誤。
//Date finder
var day = new Date();
day = day.substring(4, 100);
//Pause function for later use
function sleep(ms) {
var currentTime = new Date().getTime();
while (currentTime + ms >= new Date().getTime()) {
alert("Please be patient while we connect...");
}
}
//Sets cookie with cookie name, cookie value, and cookie expiry (converted into milliseconds by function)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
//Uses a while loop to search through cookies outputed by "document.cookie" and find desired cookie
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
//Option to delete cookies if client desires
function deleteCookie(del) {
if (del == "Y") {
var checkDel = confirm("Are you sure? Your username will be lost.");
if (checkDel === false) {
document.cookie = "username=; day";
}
}
}
//User input area - either uses cookie to identify user or requests user to input value
function checkCookie() {
var user = getCookie("username");
if (user !== "") {
alert("Welcome again " + user);
var clearCookie = prompt("Do you wish to remove your cookie from this site?", "Y or N").toUpperCase();
deleteCookie(clearCookie);
} else {
user = prompt("Please enter your name:").toUpperCase(0,1);
if (user !== "" && user !== null) {
setCookie("username", user, 91);
}
}
}
alert("Please wait while we connect you to our servers.\nPress ENTER to initiate.");
console.log("Logging onto system...");
sleep(3800);
console.log("User request: " + Math.floor(Math.random()*10000) + "; Server received request; Connection accepted; " + day);
checkCookie();
錯誤發生在這里:
var day = new Date();
day = day.substring(4, 100);
JavaScript中的日期存儲為具有許多功能的對象, substring
不是其中之一。
您可以在日期對象上使用toString()
方法,如下所示:
day.toString().substring(4, 100);
或者,您可以使用getDay()
方法,該方法返回日期實例的工作日索引:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][day.getDay()-1];
JSHint和JSLint僅識別語法錯誤。 由於以下原因,您收到的錯誤是運行時錯誤
day.substring(4, 100);
/* day is Date object which does not have any property/method called 'substring'
* therefore day.substring will be undefined
* and using undefined as a function like undefined(...) will give you error- undefined is not a function
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.