构建数据库字符串
我正在尝试根据网站上的一些任意数据构建一个数据库。它很复杂并且每个站点都会发生变化,因此我将省略详细信息。这基本上就是我想做的事情
function level0(arg) { textarea.innerHTML += arg + ' = {'; }
function level1(arg) { textarea.innerHTML += '\n\t' + arg + ': ['; }
function level2(arg) { textarea.innerHTML += arg + ', '; }
等等。问题是有些 level1 没有任何子级,我无法获得正确的格式。
我的三个问题如下。
- 结尾的逗号将在 IE 中中断(谢谢 MS)
- 如果没有任何子级,则不应打印空的 level1
- 关闭 /curly?brackets/
这是我到目前为止所拥有的演示。请注意结尾的逗号、不应打印的空 sub2
以及没有右括号或大括号
我需要重新设计整个内容吗? 还有一种方法可以将这一切都集中在一个函数中,这样我就不必担心是否添加另一层了?
编辑
这需要以字符串格式完成,我无法构建一个对象然后将其字符串化,主要是因为我需要知道我正在添加哪个元素。
I'm trying to build a database based on some arbitrary data on a website. It's complex and changes for each site so I'll spare the details. Here's basically what I'm trying to do
function level0(arg) { textarea.innerHTML += arg + ' = {'; }
function level1(arg) { textarea.innerHTML += '\n\t' + arg + ': ['; }
function level2(arg) { textarea.innerHTML += arg + ', '; }
And so on. The thing is some level1's don't have any children and I can't get the formatting right.
My three problems are as follows.
- The ending commas are going to break in IE (thank you MS)
- Empty level1's shouldn't be printed if they don't have any children
- Closing /curly?brackets/
HERE'S A DEMO of what I have so far. Notice the ending commas, the empty sub2
which shouldn't be printed, and no closing brackets or braces
Do I need to redesign the entire thing?
Is there also a way to have this all in one function so I don't have to worry if I add another layer?
EDIT
This needs to be done in a string format, I can't build an object and then stringify it, mostly because I need to know which element I'm in the middle of adding to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
总的来说,看起来您仍然可能想要构建一个对象,但如果您坚持不构建它 - 这里有一些示例解决方案:
您可以看到它的实际效果 这里。
Overall it looks that you still might want to build an object, but in case you insist on not building it - here is some sample solution:
You could see it in action here.
我不知道为什么你要使用字符串连接来构建看起来像带有嵌套数组的对象。像这样的事情会简单得多,因为它不需要修复尾随逗号等:
编辑:我已经更新了代码以使其跟踪放入的最后一个级别。
像这样使用:
我已经在你链接的演示,它工作得很好。
I'm not sure why you're building what looks like objects with nested arrays, using string concatenation. Something like this would be much simpler, since it wouldn't require fixing trailing commas, etc:
Edit: I've updated the code to make it keep track of the last level put in.
Use like this:
I've tested this in the demo you linked and it works just fine.