向对象添加属性

时间:2016-03-09 14:50:56

标签: javascript object

我编写了这段代码并且很简单,我有一个空对象,它将包含一些其他对象作为属性,但对象保持为空并且不添加所需的属性..

let buildProfileClientValidator = function(form , rules){

    let elements = {};

    function init(){
       //Some code that works fine
       addElement(elementName , elementType);
       addElement(elementName , elementType);

        //the elements object should now have some other objects as properties  
        //but it`s empty !!!!
        console.log(elements);
     }

     function addElement(elementName , elementType){
        //this condition works fine 
        if( !elementExist(elementName) ){
        //console.log(elementName , elementType); also works fine -> the values of  elementName , elementType are present
        elements[elementName] = {
            type  : elementType,
            value : '',
            rules : (rules[elementName] == undefined) ? '' :  rules[elementName].split('|')
         };
       }
     }
 }

所以我错过了什么?!

1 个答案:

答案 0 :(得分:1)

在检查代码后,但不知道如何调用buildProfileClientValidator(具体是rules参数是什么),我可以将问题追溯到这一行:

 (rules[elementName] === undefined) ? '' :  rules[elementName].split('|')

我已经在下面的小提琴(https://jsfiddle.net/hssbsL19/40/)中修改了你的代码(以使其可测试),当我用静态值替换该行时,代码可以工作。