gpt4 book ai didi

javascript - 要在 Javascript 中以特殊格式列出的字符串

转载 作者:数据小太阳 更新时间:2023-10-29 06:02:26 25 4
gpt4 key购买 nike

我有一个字符串,其中包含逗号分隔的名称和可选值,这些值像这样分隔值:

var str = "PowerOn:On,ValidLocation, temp:25";

我想把它转换成可以通过名称访问值的对象或 json,如下所示:

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.PowerOn;
alert(result);

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a["PowerOn"];
alert(result);

Note 1: If a name doesn't have value it be true by default.

更新:

Note 2 :If a name doesn't exist in list the value of it be false: ex:

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.Alarm
//result must be false

最佳答案

var str = "PowerOn:On,ValidLocation, temp:25",
arr = str.split(','),
obj = {}

for (var i=0; i<arr.length; i++) {
var parts = arr[i].split(':');
obj[parts[0]] = parts[1] || true;
}

JSFIDDLE

关于javascript - 要在 Javascript 中以特殊格式列出的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17692414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com