Hi,

I have a function in java script like this.I want to append a comma in reason_txts only if there is second element in array

function(result_arr){
            var reason_ids="",reason_txts="";
            for(i=0;i<result_arr.length;i++){
                reason_ids+=result_arr[i].id+",";
                reason_txts+=result_arr[i].col0+",";
            }
            document.getElementById("reasonIds_disp_hdn").value= reason_ids;
            document.getElementById("appReason_text").value= reason_txts;
            document.ViewSlot.appReason_text.className="txtbox2";
        }

I tried like this,

function(result_arr){
            var reason_ids="",reason_txts="";
            for(i=1;i<=result_arr.length;i++){
                reason_ids+=result_arr[i].id+",";
                if(i == result_arr.length)
                    reason_txts+=result_arr[i].col0;
                else
                    reason_txts+=result_arr[i].col0+",";
            }
            alert(reason_txts);
            document.getElementById("reasonIds_disp_hdn").value= reason_ids;
            document.getElementById("appReason_text").value= reason_txts;
            document.ViewSlot.appReason_text.className="txtbox2";
        }

but this alert itself not coming ---> alert(reason_txts);

Eg: if the input is a and b i want a,b in reason_txts

 if the input ia a 
 i want a alone in reason_txts without any comma appended.

suggest me...

error: for loop is going beyond array size. i <= result_arr.length

Anandhikrishnan,

+= is very inefficient when used to aggregate a string from many component strings. Never ever do it this way.

Instead, aggregate the component strings in an array then use array.join(glue) to put the pieces together. By default the "glue" is ',' (comma).

function(result_arr) {
	var reason_ids = [];//equivalent to new Array()
	var reason_txts = [];//equivalent to new Array()
	for(i=1; i<=result_arr.length; i++) {
		reason_ids.push(result_arr[i].id);
		reason_txts.push(result_arr[i].col0);
	}
	document.getElementById("reasonIds_disp_hdn").value= reason_ids.join();
	document.getElementById("appReason_text").value= reason_txts.join();
	document.ViewSlot.appReason_text.className="txtbox2";
}

If you want a trailing comma on reason_ids, then use reason_ids.join() + ','; .
Airshow

Hey Airshow,

Line 5 will give error when 'i == result_array.length'.

Thanks Lucky.

I'm so glad there's somebody out there checking my work. You could have a job for life. I regret to say the wages are very poor.

Line 4 should read

for(i=1; i<result_arr.length; i++) {

Airshow

Thank you guys The join() func works nice...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.