I recently read a JS interview question, which is described as follows: Use var s1=prompt("Please enter any string", "") to obtain user input
string, try programming to "reverse" the string input by the user, and output the string.
After thinking about it, the method of the string object did not realize the reversal, but there were in the array, so the problem of mutual conversion of string and array was considered.
The built-in objects in JS include string objects (String) and array objects (Array). These two objects can realize each other through their object methods
transformed. For String objects, properties and methods for operating on strings are provided; for Array objects, properties and methods for array operations are provided
Law. Therefore, it is easy for us to implement the above interview questions.
1. Convert string to array
The split() method in String object
The function of the above method is to cut a string into several segments and return an array. In other words, you can convert a string into a numerical value. Such as:
strObj.split (split number), the parameter is a string of split numbers, use the specified split number to cut the string into several segments.
Example:
//要求输出今天是星期几 //定义一个星期字符串 var str="星期日,星期一,星期二,星期三,星期四,星期五,星期六"; //创建一个日期对象 var today=new Date(); //使用today对象的getDay()方法 var week=today.getDay(); //将星期字符串分割成一个数组 var arr=str.split(","); document.write("类型是:"+typeof(arr)+",数组的第一个元素是:"+arr[0]+"<br />"); //输出结果 document.write("今天是:"+arr[week]);
The output result is: type is: object, the first element of the array is: Sunday
Today is: Friday
2. Convert array to string and reverse array elements
The join() method of Array object
The function of the above method is to convert an array into a string. For example: arrObj.join (connection number), link an array into a word using the specified connection number
string.
Example:
var arr=["a","b","c"]; var str=arr.join("-"); document.write("类型是:"+typeof(str)+",字符串是:"+str);
The output result is: type: string, string: a-b-c
The reverse() method of Array object
The function of the above method is to reverse the order of the elements in the array. Such as: arrObj.reverse().
Example:
var arr=["a","b","c"]; arr.reverse(); document.write(arr);
The output result is: c,b,a
Finally, let’s look at the implementation code of the interview question:
/* 利用var s1=prompt("请输入任意的字符串","")可以获取用户输入 的字符串,试编程将用户输入的字符串“反转”,并且将字符串输出。 */ //接受字符串 var s1=prompt("请输入任意的字符串",""); //字符串转换为数组 var arr=s1.split(""); //利用数组对象的reverse()方法实现反转 arr.reverse(); //利用数组的join()方法转换为字符串 var str=arr.join(""); document.write(str);
Achieved results:
The above is the entire content of this article, I hope it will be helpful to everyone’s study.