0
<script type="text/javascript">
     var temp=document.getElementById("col").value;
     var temp2=temp.split("%");
     for(i=0;i<col.length;i++) {         
         val = temp2[0]+temp2[1]+temp2[2];
         /* ... */
     }
</script>

I have the above code, instead of

val = temp2[0]+temp2[1]+temp2[2];

Could it be possible to store all array values into val variable? I mean a generic way of adding values to val instead of specifying array position?

Thanks

1
  • 1
    What's the purpose of the splitting the string and then combine it again? If you just want to get rid of the %, then use var val = temp.replace(/%/g, ''). Commented Jul 26, 2011 at 9:15

4 Answers 4

2

You might want to try

temp2.join(""); // join elements with no delimiter
Sign up to request clarification or add additional context in comments.

2 Comments

This looks a very simple approach.
@Polappan: I would still like to stress Felix Kling's comment to your question as splitting and joining is more complicated than just removing all %s.
2

Would be great to know what you want to do

assuming col contains 1%2%3%4

var val = document.getElementById("col").value.split("%").join("");

val now contains 1234

var val = document.getElementById("col").value.replace(/\%/g,"");

val now contains 1234

var temp = document.getElementById("col").value.split("%");
var val = 0;
for (var i=0;i<temp.length;i++) val += parseInt(temp[i],10);

val now contains 10

1 Comment

I would suggest using parseInt(..., 10) because some numbers imply other bases.
1

You can use the slice function:

val = temp2.slice(0, 3);

4 Comments

val = temp2.slice(0, 3); instead of 0,3, could it be possible to have generic as sometimes array could contain many values.
oh, I thought you only wanted to have the first three elements. In this case, you could either use val = temp2.slice(0, temp2.length); or @pimvdb 's answer
And this is different from the much simpler temp2.join("") as posted by pimvdb how?
Yes this is simple temp2.join("")
0
var sumall = function(a, b) {return a + b}
var s = [1,2,3,4,5].reduce(sumall)

5 Comments

That is a very new function (JS 1.8, i.e. IE9) developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
@mplungjan - not so new, actually, it is supported in all modern browsers. Besides, it is quite easy to implement in older browsers. You provided a link with code snippet,actually)))
I for one cannot run IE9 so it is too new for at least one of my browsers.
@mplungjan Once again, it easy to implement in any browser. And use anytime you need it.
Sure. but worth mentioning, no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.