JavaScript 拆分字符串变量(不使用任何额外变量)
Posted
技术标签:
【中文标题】JavaScript 拆分字符串变量(不使用任何额外变量)【英文标题】:JavaScript split string variable (without using any extra variable) 【发布时间】:2014-03-25 00:29:08 【问题描述】:我正在使用 MVC 模型 (django)。我在模板中有一个从 sqlite3 数据库收集数据的 for 循环。我需要填充一个 javascript 变量(采用 JSON 格式)从数据库中拆分 radar.client
字段。此字段是一个逗号分隔值字符串。我需要将其解析为不同“子”值的 json。让我现在开始练习。
生成 json var 的代码如下所示:
var json =
"id": "1",
"name": "Server",
"children": [
% if clave_radar %
% for radar in clave_radar %
"id": " radar.key ",
"name": " radar.ap ",
"data": "": "", "": "",
"children": [
//This is where I need to split in different children
"id": "1_ radar.key ",
"name": " radar.clients ",
"data": "": "", "": "",
"children": [],
],
% endfor %
% endif %
],
;
现在让我向您展示一个示例,说明服务器中处理后的代码对于客户端的外观:
var json_test=
"id": "1",
"name": "Server",
"children": [
"id": "13",
"name": "WLT",
"data": "": "","": "",
"children": [
"id": "1_13",
"name": "081196(Intel Corporate), 68a3c4(Liteon Technology Corporation), b8d9ce(Samsung Electronics)",
"data": "": "","": "",
"children": []
,
//Children Liteon and Samsung should appear here and not packed in 1_13
]
,
],
;
这就是我努力使它看起来像的方式:
varjson_real=
"id": "1",
"name": "Server",
"children": [
"id": "13",
"name": "WLT",
"data": "": "","": "",
"children": [
"id": "1_13",
"name": "081196(Intel Corporate)",
"data": "": "","": "",
"children": []
,
"id": "2_13",
"name": "68a3c4(Liteon Technology Corporation)",
"data":
"": "",
"": ""
,
"children": []
,
"id": "3_13",
"name": "b8d9ce(Samsung Electronics)",
"data": "": "","": "",
"children": []
,
]
,
]
;
【问题讨论】:
您的问题是什么?很想投票结束这个...... 【参考方案1】:为什么你不循环客户端,像这样:
var json =
"id": "1",
"name": "Server",
"children": [
% if clave_radar %
% for radar in clave_radar %
"id": " radar.key ",
"name": " radar.ap ",
"data": "": "", "": "",
"children": [
% for client in radar.clients %
"id": "1_ radar.key ",
"name": " client ",
"data": "": "", "": "",
"children": [],
% endfor %
],
% endfor %
% endif %
],
;
【讨论】:
我已经尝试过这种方式,它将为每个字符在“081196(英特尔公司),68a3c4(Liteon Technology Corporation),b8d9ce(三星电子)”,我需要for
在这种特殊情况下发生 3 次(逗号分隔)。
我不知道它是一个字符串,无论如何你可以将 forloop 更改为: % for client in radar.clients.split(', ') % 这就是你要拆分这个字符串的原因到 3 个对象。
您正在帮助我更接近解决方案...我无法在 django 的 for 中使用 .split
。不过,我现在正在阅读如何从模型中拆分 ***.com/questions/8317537/…【参考方案2】:
我刚刚找到了解决这个问题的方法。首先我受到this how to split a string to an array with django的启发
我将此功能添加到radar
模型中:
def list_clients(self):
return self.clientes_encontrados.split('), ')
然后,代码会像这样:
var json_radar =
"id": "1",
"name": "Server",
"children": [
% if clave_radar %
% for radar in clave_radar %
"id": " radar.key ",
"name": " radar.ap ",
"data": "": "","": "",
"children": [
% if radar.clients != "null" %
% for client in radar.list_clients %
"id": "1_ radar.key ",
"name": " client ",
"data": "": "", "": "",
"children": [],
% endfor %
% endif %
],
% endfor %
% endif %
],
;
【讨论】:
以上是关于JavaScript 拆分字符串变量(不使用任何额外变量)的主要内容,如果未能解决你的问题,请参考以下文章
获取发送的命令并使用 JavaScript 将其拆分为多个变量