我为节点红色制作了一个脚本,我想让它简单地实现。如何更多地压缩这些代码?
var notDetected = "NOT DETECTED";
var models = [
context.get('model1')||notDetected,
context.get('model2')||notDetected,
context.get('model3')||notDetected,
context.get('model4')||notDetected
];
switch(msg.topic)
{
case "core_1":
models[0] = msg.model + "";
context.set('model1', models[0]);
break;
case "core_2":
models[1] = msg.model + "";
context.set('model2', models[1]);
break;
case "core_3":
models[2] = msg.model + "";
context.set('model3', models[2]);
break;
case "core_4":
models[3] = msg.model + "";
context.set('model4', models[3]);
break;
}
var msgs = [
{payload: models[0]},
{payload: models[1]},
{payload: models[2]},
{payload: models[3]}
];
return msgs;模型还能被压缩吗?味精呢?例如,我可以删除模型内部的id以匹配msgs id吗?
msg[x] = {payload: models[x]};有可能吗?
发布于 2018-02-05 01:27:22
根据可读性/可扩展性(不一定是空间)压缩代码:
models和msgs数组,core_X字符串以获取索引,但如果不验证输入,则可能会导致安全性问题;或者可以使用从四个字符串core_1到实际数字的映射。在这里查看for循环:for.asp
看起来可能是这样的:
var msgs = [];
for (x = 0; x < 4; x++) {
msgs[x] = {payload: models[x]};
}发布于 2018-02-05 01:30:46
您可以将context.get()包装在一个函数中,并在您的模型数组中重用它,这样在对其进行更改时,就不必更改数组中的每个索引。
示例:
var notDetected = "NOT DETECTED";
var getContext = function(str) {
return context.get(str) || "NOT DETECTED";
}
var models = [
getContext('model1'),
getContext('model2'),
getContext('model3'),
getContext('model4'),
];如果需要更改context.get(),只需在函数中修改一次,如下所示:differentContext.get(str) || "NOT DETECTED"
如果没有这些,你就必须改变每一个指数:
var models = [
differentContext.get('model1')||notDetected,
differentContext.get('model2')||notDetected,
differentContext.get('model3')||notDetected,
differentContext.get('model4')||notDetected
];发布于 2018-02-05 01:27:56
因此,经过一点思考,我创建了一个脚本,它只需将4条消息重定向到它们需要到达的位置,然后在另一个脚本中使用所需的参数,或者从整个msg中获取msg.model。以下是拆分器代码:
var notDetected = {};
var msgs = [
context.get('msg1')||notDetected,
context.get('msg2')||notDetected,
context.get('msg3')||notDetected,
context.get('msg4')||notDetected
];
switch(msg.topic)
{
case "core_1":
context.set('msg1', msg);
break;
case "core_2":
context.set('msg2', msg);
break;
case "core_3":
context.set('msg3', msg);
break;
case "core_4":
context.set('msg4', msg);
break;
}
return msgs;在文本节点中,我只是设置为使用msg.model值。现在我得到了更有用的拆分器。
https://stackoverflow.com/questions/48614643
复制相似问题