如何将键值与while循环组合

How to combine for key value with while loop?

本文关键字:while 循环 组合 键值      更新时间:2023-09-26

每次与对象数组和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');
        }
    }
};

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

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

看看这个小提琴的例子。