假设我们有一种特殊的字符串,如下所示:
const str ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";
我们需要编写一个JavaScript函数,使用String.prototype.split()方法将上述字符串转换为以下数组-
const arr = [ { "Integer":1, "Float":2.0 }, { "Boolean":true, "Integer":6 }, { "Float":3.66, "Boolean":false } ];
我们必须使用以下规则进行转换-
--- \n marks the end of an object --- one whitespace terminates one key/value pair within an object --- ',' one comma separates the key from value of an object
以下是代码-
const str ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False"; const stringToArray = str => { const strArr = str.split('\n'); return strArr.map(el => { const elArr = el.split(' '); return elArr.map(elm => { const [key, value] = elm.split(','); return{ [key]: value }; }); }); }; console.log(stringToArray(str));
输出结果
这将在控制台中产生以下输出-
[ [ { Integer: '1' }, { Float: '2.0' } ], [ { Boolean: 'True' }, { Integer: '6' } ], [ { Float: '3.66' }, { Boolean: 'False' } ] ]