{x : 425, y:25}
我有一个像“425,25”这样的字符串,我需要这样的输出
{x: 425, y:25}
You can use .split()
and .map()
functions. Consider the steps mentioned below:
.split()
function by passing comma ,
as delimiter.Number
function that will convert strings to corresponding numeric values. let data = "425,25", [x, y] = data.split(",").map(Number), result = {x, y}; console.log(result);
How about that? with ES6 Rename Object Keys in Javascript
//{x: 425, y:25} const arr = "425,25".split(',').map(Number); //maps value to Number after split const {0: x,1: y} = {...arr}; // make array to object and rename keys ie x,y const result = {x,y} // wrap variable to object console.log(result); // your expected result
You can split a string using the string's .split method . This will give you an array with the two strings '425'
and '25'
. You can then parse them into integers using parseInt , and create an object with them:
const input = '425,25'; const substrings = input.split(','); const result = { x: parseInt(substrings[0], 10), y: parseInt(substrings[1], 10), }; console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.