Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to create some rules in javascript as below. I want to do create these rules in for loop however I couldn't able to dynamically create the variable parts.

var _docmap = document.mappingsTanimlari;
    if(_docmap.addServerOrClusterValue0.value != ""){
        arr.push(_docmap.addServerOrCluster0.value + _docmap.addServerOrClusterValue0.value)
    }
    if(_docmap.addServerOrClusterValue1.value != ""){
        arr.push(_docmap.addServerOrCluster1.value + _docmap.addServerOrClusterValue1.value)
    }
    if(_docmap.addServerOrClusterValue2.value != ""){
        arr.push(_docmap.addServerOrCluster2.value + _docmap.addServerOrClusterValue2.value)
    }
    if(_docmap.addServerOrClusterValue3.value != ""){
        arr.push(_docmap.addServerOrCluster3.value + _docmap.addServerOrClusterValue3.value)
    }
    if(_docmap.addServerOrClusterValue4.value != ""){
        arr.push(_docmap.addServerOrCluster4.value + _docmap.addServerOrClusterValue4.value)
    }
share|improve this question

closed as not a real question by casperOne Nov 12 '12 at 14:24

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers 2

up vote 0 down vote accepted

First of all, I've to say that code looks horrible, but here's how to do it. You need to use bracket notation instead of dot notation so you can pass a string and concatenate the index:

for ( var i = 0; i <= 4; i++ ) {

  if ( document.mappingsTanimlari[ 'addServerOrClusterValue'+ i ].value ) {
    ...
  }

}
share|improve this answer
    
Thank you. I know it looks horrible because of that i needed to do it in for loop. –  user1811601 Nov 9 '12 at 8:54
    
Yah, glad to help. I'd suggest you abstract the code into a function and cache the objects in variables so it reads more clearly. –  elclanrs Nov 9 '12 at 8:56

Why not do it like this?

var arr = new Array();
var data = document.mappingsTanimlari;

for(var i=data.length;i--;) {
 if(data[i].value != "") {
  arr.push(data[i].value + data[i].value);
 }
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.