Why does the code fire three times and add nine items?

  • 0
    My code
    var lvl1 = {
    '-': [], 
    '+': [] 
    } ;
    var lvl2 = {
    '~': lvl1, 
    '=': lvl1, 
    }
    var lvl3 = {
    'obj1':lvl2,  
    'obj2':lvl2,  
    'obj3':lvl2,  
    }
    var test1 = 'cor1[car1,-car2]cor2{<cop1,cop2,-cop3>}-cor3(cat3)cor4';
    
    console.log(test1)
    
    var text_default = test1.match(/(?<=^|\)|]|})[^\(|[|{]+/g);
    var text_tag = test1.match(/(?<=\[).+?(?=\])/g);
    var text_title = test1.match(/(?<=\{).+?(?=\})/g);
    var text_author = test1.match(/(?<=\().+?(?=\))/g);
    
    
    function add_plus_minus(way,arr){
    	$.each(arr, function(index2, value2 ) {
    		$.each(value2.split(','), function(index22, value22 ) {
    			var first = value22.slice(0,1)
    			var word = value22.replace(/[^A-Za-z0-9_]/g, "");
    			if(first=='-'){
    				lvl3[way[0]][way[1]]['-'].push(word);
    				alert('v')
    				console.log([way[0],way[1],'-']);
    				console.log(word);
    			}
    			else{
    				//lvl3[way[0]][way[1]]['+'].push(word);
    				//console.log([way[0],way[1],'+']);
    				//console.log(word);
    			}
    		});
    	});
    }
    
    
    function add_or_and(way,arr){
    	$.each(arr, function(index, value ) {
    		var and_arr = value.match(/(?<=^|\>)[^\<]+/g);
    		if(and_arr!=null){
    			add_plus_minus([way,'='],and_arr);
    		}
    		var or_arr = value.match(/(?<=\<).+?(?=\>)/g);
    		if(or_arr!=null){
    			add_plus_minus([way,'~'],or_arr);
    		}
    	});
    }
    
    var default_name = 'obj1';
    if(text_default!=null){
    console.log(text_default);
    add_or_and(default_name,text_default);
    }
    if(text_title!=null){
    console.log(text_title);  
    add_or_and('obj1',text_title);
    }
    if(text_author!=null){
    console.log(text_author);  
    add_or_and('obj2', text_author);
    }
    if(text_tag!=null){
    console.log(text_tag); 
    add_or_and('obj3',text_tag);
    }
    console.log(lvl3);

    The code had to add three elements.
    cor3 to lvl3 ["obj1"] ["="] ["-"]
    cop3 in lvl3 ["obj1"] ["~"] ["-"]
    car2 to lvl3 ["obj3"] ["="] ["-"]
    But I don't understand what went wrong?
    The code has added all three elements to each obj.
    JavaScript Anonymous, Dec 14, 2019

  • 1 Answers
  • 0
    Not surprisingly, you have all three properties of the lvl3 object referring to the same lvl2 object. In other words, with this notation lvl3 [way [0]] [way [1]] you always work with one object, and you need to separate.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!