ben*_*ben 2 javascript string variables concatenation pug
是否有一种很好的,干净的方法将字符串和变量连接成 Jade可以理解的变量名?
理想情况下,它看起来像这样:
each #{shape + 'Text'} in #{shape + 'Texts'}
li #{shape + 'Text'}
Run Code Online (Sandbox Code Playgroud)
我试过使用,window[shape + 'Text']但似乎没有用.也许我做错了?
这就是我想要这样做的原因:
我有一个名为的数组shapes,如下所示:['square', 'triangle', 'circle']
我正在使用Jade的each ... in ...函数来遍历这个数组.在我的函数的每次迭代中,我需要做each ... in ...一些其他几个数组中的另一个.而是采用了直线上升的变量来选择遍历哪个数组,像each shape in shapes,我想连接shape,以获得像一个字符串each squareText in squareTexts或each circleText in circleTexts.
目前,我正在使用条件来实现我想要的结果,但它是冗长的而不是语言的极简主义精神.
提前感谢任何建议.
所以看起来在我的情况下,诀窍是使用Javascript的eval()函数将变量名和字符串连接成一个新的变量名.这是我成功(和简洁)的实现.
- var items = eval(shape + 'Texts');
each item, i in items
li #{items[i]}
Run Code Online (Sandbox Code Playgroud)