简体   繁体   English

从一个中获取3个变量

[英]Get 3 Variables out of one

I have a problem... I have the following variable (type: string): {"friendCount":5,"pnCount":0,"allCount":5} 我有问题...我有以下变量(类型:字符串): {“ friendCount”:5,“ pnCount”:0,“ allCount”:5}

My goal is it, to have 3 variables with friendCount, pnCount and allCount and i don't know, how I can do this. 我的目标是,拥有3个带有friendCount,pnCount和allCount的变量,我不知道我该怎么做。 This looks as an object, but it's only a string (planned) 它看起来像一个对象,但只是一个字符串(已计划)

I think that I have to do it with RegEx or something but I have no further Idea... 我认为我必须使用RegEx或其他东西来做,但是我没有进一步的想法...

The numbers in the string may be between 0 and about 100 字符串中的数字可能在0到大约100之间

I hope, that you understand my problem and can help me :) 希望您能理解我的问题并能为我提供帮助:)

If that is a string, than parse it... 如果那是一个字符串,那么就解析它...

var str = '{"friendCount":5,"pnCount":0,"allCount":5}';
var obj = JSON.parse(str);
console.log(obj.friendCount, obj.pnCount, obj.allCount);

If it is already an object, just reference it 如果已经是对象,则只需引用它

var obj = {"friendCount":5,"pnCount":0,"allCount":5};
console.log(obj.friendCount, obj.pnCount, obj.allCount);

Try this 尝试这个

var data= {"friendCount":5,"pnCount":0,"allCount":5}

var friendCount = data.friendCount;
var pnCount = data.pnCount;
var allCount = data.allCount;

If you want Regex it can be done like this : 如果你想正则表达式可以做到像这样

var re = /([\w]+)":(\d+)/g; 
var str = '"friendCount":5,"pnCount":0,"allCount":5';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM