从关联数组和长字符串构造javascript数组

时间:2014-06-09 09:06:16

标签: javascript arrays regex string

我有一个类似

的javascript assoc数组(对象)
aa = {"(one)":["a","b","c"], "(two)":["d","e","f"]}

之类的字符串
s = "(two) blah blah (one) etc (two)"

我想将assoc数组转换为一个普通数组,其顺序如字符串

中所指定
newarray = [["d","e","f"] , ["a","b","c"], ["d","e","f"]]

唯一的事情是,数组和字符串可能包含数百万个项目。如果我使用带有全局修饰符的string.match来执行此操作,然后迭代结果,我最终会使用大量内存吗?有没有办法迭代字符串中的匹配而不存储所有匹配的文本(有点像string.search的迭代器版本)?

2 个答案:

答案 0 :(得分:1)

var aa = {"(one)":["a","b","c"], "(two)":["d","e","f"]};
var s = "(two) blah blah (one) etc (two)"
var newarray = [];
var res = s.match(/\((.*?)\)/g);
var i = 0;
while (i < res.length){
    newarray.push(aa[res[i]]); 
    i++;
}
console.log(newarray);

最后这个完美无缺。

http://jsfiddle.net/KRzRj/

答案 1 :(得分:1)

基于正则表达式,我正在思考这些问题:

var aa = {"(one)":["a","b","c"], "(two)":["d","e","f"]};
var s = "(two) blah blah (one) etc (two)";
var result = [];

s.match(/(\(.+?\))/g).forEach(function(match) {
    result.push(aa[match]);
});