gpt4 book ai didi

javascript - 如何将 for key value 与 while 循环结合起来?

转载 作者:行者123 更新时间:2023-12-03 08:13:47 24 4
gpt4 key购买 nike

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

看看这个example fiddle .

关于javascript - 如何将 for key value 与 while 循环结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com