JavaScript string and array conversion functions [do not use split and join] _ javascript skills

Source: Internet
Author: User
Tags javascript array
The following code has a good idea without considering the running efficiency. But in actual applications, we still use split or join to implement Array Operations. Two custom js functions that implement mutual conversion between strings and arrays hope to be useful to you:

The Code is as follows:


Function StringToArray (str, substr ){
/* Function: Splits a string into an Array Based on the specified string.
Parameters:
Str: string to be converted
Substr: Split string
Return Value:
Converted Array
*/
Var arrTmp = new Array ();
If (substr = ""){
ArrTmp. push (str );
Return arrTmp;
}
Var I = 0, j = 0, k = str. length;
While (I J = str. indexOf (substr, I );
If (j! =-1 ){
If (str. substring (I, j )! = "") {ArrTmp. push (str. substring (I, j ));}
I = j + 1;
} Else {
If (str. substring (I, k )! = "") {ArrTmp. push (str. substring (I, k ));}
I = k;
}
}
Return arrTmp;
}

Function ArrayToString (arr, str ){
/* Function: convert an array to a string based on the delimiter (string ).
Parameters:
Arr: String Array to be converted
Str: Split string
Return Value:
Converted string
*/
Var strTmp = "";
For (var I = 0; iif (arr [I]! = ""){
If (strTmp = ""){
StrTmp = arr [I];
} Else {
StrTmp = strTmp + str + arr [I];
}
}
}
Return strTmp;
}


For more information about the application, see the related articles of the home of the foot.
Javascript array summary using call Methods
Http://www.jb51.net/article/13084.htm

Practical Tips for javascript Array Operations
Http://www.jb51.net/article/19987.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.