我試圖只是讓表單輸入(主要用於實踐和嘗試不同的事物)一點點驗證爲什麼我無法在空數組上調用Array.prototype.map?
我的代碼:
var Validator = function() {
this.elements = {};
this.alerts = [];
}
Validator.prototype = {
hookElement: function() {
var that = this;
$('#'+elementid).on('keyup', function(e) {
if (that.elements[name].val().length > that.elements[name].options.maxLength) {
that.alerts.map(function(x) {
if (x.name === name && x.option === 'maxLength') {
return true;
} else {
that.alerts.push({
'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength,
'name': name,
'option': 'maxLength',
'visible': true
});
}
});
} else {
// Yet to add remover function
}
});
}
當我按在輸入字段中鍵,數組從來沒有地圖(確定一些console.log
調試)爲什麼它沒有通過它,我知道它應該在數組中的每個元素上執行一個函數,但如果沒有元素它真的什麼都不做?我該如何做這項工作。
這個想法是這樣的:如果對象已經存在於數組中,它不會添加到數組中。
編輯: 粘貼完整的代碼在這裏,但我不認爲這將是相關的: 很抱歉的縮進,這不是在崇高的文本
var Validator = function() {
this.elements = {};
this.alerts = new Array();
}
Validator.prototype = {
hookElement: function(elementid, name, options) {
if (options === "object" || options === undefined) {
if (typeof options === "object" || options === undefined) {
if (elementid != undefined || name != undefined) {
this.elements[name] = $('#'+elementid);
this.elements[name].name = name;
this.elements[name].options = options || {
maxLength: 5,
smallLength: 5,
partner: undefined,
regex: undefined,
uppercase: undefined,
lowercase: undefined
};
var that = this;
$('#'+elementid).on('keyup', function(e) {
if (that.elements[name].val().length > that.elements[name].options.maxLength) {
that.alerts.map(function(x) {
if (x.name === name && x.option === 'maxLength') {
return true;
} else {
that.alerts.push({
'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength,
'name': name,
'option': 'maxLength',
'visible': true
});
}
});
} else {
}
});
} else {
return console.log('Missing Arguments');
}
} else {
return console.log('Options argument must be an object please visit the API page.');
};
};
},
hookForm: function(elementid, alertid, options) {
var li = document.createElement('li');
var ul = document.createElement('ul');
ul.id = 'alertsList';
if (document.getElementById(ul.id) === null) {
document.getElementById(alertid).appendChild(ul);
}
var alertsExist = [];
var that = this;
if (elementid != undefined) {
$('#'+elementid).on('keyup', function() {
console.log(that.alerts);
for (var i = 0; i < that.alerts.length; i++) {
if (alertsExist.indexOf(that.alerts[i].name + ' ' + that.alerts[i].alert) === -1) {
li.id = that.alerts[i].name + that.alerts[i].option;
li.innerHTML = that.alerts[i].alert;
document.getElementById('alertsList').appendChild(li);
alertsExist.push(that.alerts[i].name + ' ' + that.alerts[i].alert);
}
}
});
}
}
}
var test = new Validator();
test.hookElement('userEmail', 'Email');
test.hookElement('userPassword', 'Password');
test.hookForm('createForm', 'alerts');