如何将键值与while循环结合起来?

时间:2015-12-02 10:30:49

标签: javascript

每次与对象数组和JSON文本键匹配时,我都会尝试控制日志test

它会记录对象数组中的每个标记,但是while循环并不像预期的那样工作。

一个工作示例:http://codepen.io/Caspert/pen/PZYjPV?editors=001

var text_buffer = raw_content.text;

var raw_content = {
    "text": "Test image 1 [image] Test image 2 [image] Test image 3 [image] Test image 4 [image]",
    "media": [{
        "image": {
            "src": "http://placehold.it/400x200",
            "caption": "This is a caption"
        }
    }, {
        "image": {
            "src": "images/gallery/sh0.png",
            "caption": "This is a caption"
        }
    }, {
        "image": {
            "src": "http://placehold.it/400x200",
            "caption": "This is a caption"
        }
    }, {
        "image": {
            "src": "images/gallery/sh0.png",
            "caption": "This is a caption"
        }
    }]
};

// Find multiple tags
var tags = {
    "image": '[image]',
    "gallery": '[gallery]'
};

for (var key in tags) {
    if (tags.hasOwnProperty(key)) {
        var tag = tags[key];
        console.log('tag = ', tag);

        while (text_buffer.indexOf(tag) !== -1) {
            console.log('test');
        }
    }
};

1 个答案:

答案 0 :(得分:1)

您的while循环将挂起,因为indexOf将始终搜索tag变量的第一个实例,该变量将始终存在。最好的方法是通过指定要搜索的起始索引:

var startIndex = -1;

while ((startIndex = raw_content.text.indexOf(tag, startIndex + 1)) != -1) {
  console.log('test');
}

看看这个example fiddle