拆分字符串并遍历结果

JS - Splitting a string and looping through results

本文关键字:遍历 结果 串并 字符串 字符 拆分      更新时间:2023-09-26

在JS中,我遇到了如何拆分来自AJAX调用的字符串的问题。

这是我目前为止写的:

xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();

你有/////…将脚本…/////在上面的脚本中,我需要添加一个小函数来拆分AJAX调用返回的字符串。

字符串只包含div的名称,如下所示:

feedUpdateResponse = "div1/div2/div3/div4"

我想首先通过它的斜杠(/)分割字符串,并通过不同的值运行一个循环,并对我的页面上的这些元素做一些事情。

给我一个想法,我需要实现,我已经给出了这个例子,这是一个混合的ASP &JS -这是我唯一能描述它的方法(并表明我已经尝试过):)

MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next

在我的页面上,我有一个ASP脚本,产生jquery旋转木马,所有由单独的div包含。这些div被命名为DIV1、DIV2等。例如,在DIV1内部,有一个名为updateAvailable_div1的文本元素,它将提醒用户"此提要有新照片可用,请单击刷新按钮"。

有人能向我解释一下我如何能改变我的例子上面的工作在JS?只需要将字符串分割成一个数组,然后循环分割后的值…

您可以使用.split()在指定字符上拆分字符串,并将结果作为数组返回。接下来就是循环遍历数组:

// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
    i;
for (i = 0; i < a.length; i++) {
    document.getElementById("updateAvailable_" + a[i]).style.visibility
                                                                 = "visible";
}

通过string.split("/")获取您的数组。使用选择的方法迭代数组。我更喜欢Array.forEach():

feedUpdateResponse.split("/").forEach(function (item) {
    document.getElementById(item).style.visibility = "visible";
});

请参阅在旧浏览器中使用.forEach()的兼容性说明。

作为备选:

for(element of feedUpdateResponse.split("/")){
    do_your_thing();
}

使用for..in最终会给你数组的索引(键),而for..on会给你数组的元素(值)。

你也可以这样做:

for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
    do_your_thing();
}

如果你需要索引。

缺点是它不兼容IE,但对于个人项目或快速自动化脚本,它通常做得很好。

试试下面的代码:

var a = feedUpdateResponse.split("/");
for (i in a) {
    document.getElementById("updateAvailable_" + a[i]).style.visibility
                                                                 = "visible";
}
var feedUpdateResponse = "div1/div2/div3/div4";
var feedUpdateSplit = feedUpdateResponse.split("/");
for (var x = 0; x < feedUpdateSplit.length; x++) {
  document.getElementById("updateAvailable_" + feedUpdateSplit[x]).style.visibility = "visible";
}