为什么我不能在空数组上调用Array.prototype.map?

时间:2014-09-05 04:35:59

标签: javascript arrays

我试图为表单输入做一个小验证器(主要用于练习和尝试不同的东西)

我有代码:

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调试确定)为什么不通过它,我知道它应该对数组中的每个元素执行一个函数但是如果没有元素它真的什么都不做?我怎样才能做到这一点。

这个想法是,如果对象已经存在于数组中,它将不会添加到数组中。

修改 在这里粘贴完整的代码,但我认为它不相关: 对于缩进感到抱歉,Sublime Text

并没有那么糟糕
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');

1 个答案:

答案 0 :(得分:3)

您使用Array.prototype.map功能的方式并非如此。回调只会应用于数组项,所以它确实不会触发空数组。除此之外,你操纵你在回调中映射的数组,这是一个坏主意。

您应该使用Array.prototype.find(更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)查看该项目是否已存在于数组中,如果不存在,请执行that.alerts.push逻辑。

编辑:代码:(未经测试)

$('#'+elementid).on('keyup', function(e) {
    if (that.elements[name].val().length > that.elements[name].options.maxLength) {
        if (!that.alerts.find(function (x) {
             return x.name === name && x.option === 'maxLength';
        })) {
             // Item not yet in the array, so push it
             that.alerts.push({
                 'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength,
                 'name': name,
                 'option': 'maxLength',
                 'visible': true
             });
         }
     }
 });