[英]How to create a text string using foreach loop?
Trying to create text string from interface to display into UI, Below code is creating separate file for each interface, How do i creat single file as i have given in the expected.尝试从界面创建文本字符串以显示到 UI 中,下面的代码为每个界面创建单独的文件,我如何按照预期创建单个文件。
Also is there way to create UI to display typescript code as a sample instead of using text string?还有没有办法创建 UI 来显示 typescript 代码作为示例而不是使用文本字符串?
main.js main.js
var path = "/filepath"
var data = [
{
name: "IParam"
},
{
name: "IError"
}
]
function createInterfaces(path, data) {
var _text = 'import { ';
$.each(data,function(id,val){
_text += val.name + '}' + 'from ' + path + ';\n\n';
});
return _text;
}
Expected Result should be预期结果应该是
"import { IParam, IError} from '/filePath'";
You should move the last bit out of your for loop您应该将最后一点移出 for 循环
function createInterfaces(path, data) {
var _text = 'import { ';
$.each(data,function(id,val){
_text += val.name;
});
_text += '}' + 'from ' + path + ';\n\n'
return _text;
}
Another way to do it would be -另一种方法是-
function createInterfaces(path, data){
const imports = data.map(d => d.name).join(', ');
return `import { ${imports} } from '${path}';\n\n`;
}
Here's the snippet to check -这是要检查的片段 -
var path = "/filepath" var data = [ { name: "IParam" }, { name: "IError" } ] function createInterfaces(path, data){ const imports = data.map(d => d.name).join(', '); return `import { ${imports} } from '${path}';\n\n`; } console.log(createInterfaces(path, data));
You should call Array.prototype.map
on the data
array and return each name
, then join the results.您应该在data
数组上调用Array.prototype.map
并返回每个name
,然后加入结果。
var path = "/filepath" var data = [ { name: "IParam" }, { name: "IError" } ] function createInterfaces(path, data) { return "import { " + data.map(d => d.name).join(', ') + " } from '" + path + "';\n\n" } console.log(createInterfaces(path, data))
You can use the array.map
to create the string and assign teh result to text
variable.您可以使用array.map
创建字符串并将结果分配给text
变量。
text += `import { ${data.map(a => a.name).toString()} } from '${path}' `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.