我正在创建代码以将字符串转换为字典和数组,并将数组和字典转换为字符串。
字符串到数组有效,字符串到 Obj(字典)有效,数组到文本有效,但 obj 到字符串(文本)无效。我被卡住了,我不知道如何解决它。我测试了代码,但结果并不好。
function strToArray(string) { let array = []; for (var element of string) { array.push(element); } return array; }; function strToObj(string) { let dict = {}; for (let i = 0; i < string.length; i++) { let letter = string[i]; if (dict[letter]) { dict[letter].push(i); } else { dict[letter] = [i]; } } return dict; }; function arrayToString(array) { let text = ""; for (var element of array) { text = text + element; } return text; }; function objToString(obj) { let text = ""; //for(i = 0; i < obj.length; i++){ //text = text + arrayToString(obj[i]); //} for (var element in obj) { let value = obj[element]; } return text; }; const ArrayHello = strToArray('hello'); const ObjHello = strToObj('hello'); const HelloArray = arrayToString(ArrayHello); const HelloObj = objToString(ObjHello); console.log(ArrayHello); console.log(ObjHello); console.log(HelloArray); console.log(HelloObj);
您可以使用数组来创建字符串,并且可以重用arrayToString()方法,并且可以很容易地得到答案,如下所示:
arrayToString()
function strToArray(string) { let array = []; for (var element of string) { array.push(element); } return array; }; function strToObj(string) { let dict = {}; for (let i = 0; i < string.length; i++) { let letter = string[i]; if (dict[letter]) { dict[letter].push(i); } else { dict[letter] = [i]; } } return dict; }; function arrayToString(array) { let text = ""; for (var element of array) { text = text + element; } return text; }; function objToString(obj) { let text = []; for (let [key, index] of Object.entries(obj)) { for (let i of index) { text[i] = key; } } return arrayToString(text); }; const ArrayHello = strToArray('hello'); const ObjHello = strToObj('hello'); const HelloArray = arrayToString(ArrayHello); const HelloObj = objToString(ObjHello); console.log(ArrayHello); console.log(ObjHello); console.log(HelloArray); console.log(HelloObj);
更新:
您也可以使用方法轻松 Array.prototype.join实现功能[MDN LINK]arrayToString
Array.prototype.join
arrayToString
const array = ['h', 'e', 'l', 'l', 'o']; const arrayToString = (arr, delimiter = '') => arr.join(delimiter); console.log(arrayToString(array));