- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的需要是将包含字符串的数组解析为eval()
。我了解 eval()
安全威胁并假设 in this question一切都很好。
该数组由 PHP 脚本在服务器端创建,该脚本会查找一堆指定的文件夹,使用 file_gets_contents()
加载每个文件,并将每个内容注入(inject)到数组的一行中。然后它将最终的数组发送给客户端。
在我的设计中,有优点也有缺点,数组中的一些脚本用于初始化一些对象,其他脚本则使用对象进行逻辑。为了使其顺利工作,正如您所期望的,必须以正确的顺序进行eval()
编辑。否则 javascript 会抛出错误。
我的问题如下:数组中的脚本是无序的。由于特定原因,超出了此处的范围,我不想既不订购数组服务器端,也不向客户端传递任何指示(例如 array[key]
) 告诉它如何重新组织收到的无序脚本。
相反,我正在尝试建立一种能够解析数组的机制,将所有太早出现的脚本发送到队列中,eval()
其他脚本,最后 eval()
队列的其余部分。
到目前为止,我的想法是在 Array.forEach()
语句中try ... catch
每个eval()
, splice()
数组删除每个已经正确eval()
ed的脚本,让有错误的脚本留在数组中,然后调用 Array.forEach()
直到 array.length === 0
;
作为一个案例研究,我正在寻找在循环中解析数组示例的每一行的能力,决定splice()
该行(因为删除
并没有真正删除...)或将其放入数组中,然后重新循环以检查行是否存在。
为了说明我的观点,我提供了这些不起作用的示例。仍在调试中...
this.a = [ //the array that reproduce the situation (seems to work)
'o = {}', // I declare o as a global namespace
'o.a.b.c = "a string"', //I declare a value in o.a.b.c, too early
'o.a.b = {}', //I declare o.a.b, but o.a doesn't exist
'o.a = {}', //I declare o.a, too late
];
var build = function(value,key,array){
try{
eval(value);
this.a = array.slice(key);
}catch(error){
console.log(error.message);
this.a.push(value);
}finally{
if(this.a.length === 1) this.a = [];//Take care of infinite loop risk, as the "while" below does not carry the variable to zero...
}
}.bind(this);
while(this.a.length > 0){
this.a.forEach(build);
console.log(this.a.length);
};
console.log(this.a);
逻辑能力强的人可以帮忙吗?
最佳答案
您的脚本存在一些问题:
this.a = array.slice(key);
似乎没有任何意义?this.a = array.push(value);
将 a
设置为数组的长度if(this.a.length === 1) this.a = [];
- 不确定您要在这里保护什么无限循环?this.a.forEach(build);
如果您在循环遍历数组时尝试修改数组,听起来是个坏主意。我的方法会简单得多 - 只需使用数组作为队列:
this.a = [ //the array that reproduce the situation (seems to work)
'var o = {}', // I declare o as a global namespace
'o.a.b.c = "a string"', //I declare a value in o.a.b.c, too early
'o.a.b = {}', //I declare o.a.b, but o.a doesn't exist
'o.a = {}', //I declare o.a, too late
];
while (this.a.length) {
var value = this.a.shift();
try {
(null, eval)(value);
} catch(error) {
if (error instanceof SyntaxError) break;
this.a.push(value);
}
}
关于javascript - 逻辑: Make mechanism to parse a javascript array until each row has been taken under account,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29402233/
我是一名优秀的程序员,十分优秀!