Javascript 返回某个索引
我有下面的代码,其中函数getImageNum接收一个连接URL的数组,因此我将这些URL拆分为一个符号,以便将它们分开。 我的变量res=path.split(“-”)保存分离的URL。因此res[0]给出了一个如下所示的url示例:。 但我的问题是,我想获取res变量中的每个url,以便在幻灯片放映中使用它。因此,我希望能够使用一个自动保留不同索引的变量,而不是res[0]。请参见下面的代码了解想法Javascript 返回某个索引,javascript,jquery,Javascript,Jquery,我有下面的代码,其中函数getImageNum接收一个连接URL的数组,因此我将这些URL拆分为一个符号,以便将它们分开。 我的变量res=path.split(“-”)保存分离的URL。因此res[0]给出了一个如下所示的url示例:。 但我的问题是,我想获取res变量中的每个url,以便在幻灯片放映中使用它。因此,我希望能够使用一个自动保留不同索引的变量,而不是res[0]。请参见下面的代码了解想法 function getImageNum(imageArray) { var path;
function getImageNum(imageArray) {
var path;
var res;
var index = 0;
for (i in imageArray) {
path = imageArray[i];
}
res = path.split("-");
$("#ContentPlaceHolder1_ContentPlaceHolder1_imageView").attr("src", res[index++]);
}
守则:
$("#ContentPlaceHolder1_ContentPlaceHolder1_imageView").attr("src", res[index++]);
只返回相同的图像,而不遍历整个res内容
for (i in imageArray) {
path = imageArray[i];
}
此代码将循环遍历imageArray
中的每个图像,然后每次将path
覆盖到最新的图像。如果您想在路径中附加更多的文本,而不是完全替换它,则需要对每个循环进行concat。但是,看起来您只想在res
变量中存储一个包含所有路径的数组,那么为什么还要处理字符串呢
for (i in imageArray) {
res.push(imageArray[i]);
}
其次,
index++
不会自动迭代所有索引,它只是一个运算符,在它给出旧值后增加该值。如果您想要所有图像,您必须手动循环使用res
中的每个图像。如果我了解您想要的是什么,因为它不太清楚,您的循环有问题
正如Lochemage之前所说的那样,在for循环外部使用变量在for循环内部获取其值将不起作用
var imageArray = ["http://www.example.com/img1-http://www.example.com/img2-http://www.example.com/img3-http://www.example.com/img4","http://www.example.com/img5-http://www.example.com/img6-http://www.example.com/img7-http://www.example.com/img8-http://www.example.com/img9"];
// this is what I assume is your array
var imageArrayNew = [];
for(i=0; i<imageArray.length; i++) {
res = imageArray[i].split("-");
for(j=0; j<res.length; j++) {
imageArrayNew.push(res[j]);
}
}
// now imageArrayNew is an array that contains Each of the elements in imageArray and you can do stuff with it
var-imageArray=[”http://www.example.com/img1-http://www.example.com/img2-http://www.example.com/img3-http://www.example.com/img4","http://www.example.com/img5-http://www.example.com/img6-http://www.example.com/img7-http://www.example.com/img8-http://www.example.com/img9"];
//这就是我假设的数组
var imageArrayNew=[];
对于(i=0;i您希望幻灯片放映如何工作…例如每两秒钟更改一次图像扫描您请做一把小提琴?我已经编写了制作幻灯片的代码,这会每5秒钟更改一次图像。我只需要将url添加到src属性,然后幻灯片将在您说:res.push时显示图像(imageArray[i]);您只有一长串连接的URL。因此我需要拆分它们。我的代码可以正常工作,但可能只有在这种情况下才能正常工作。问题是如何将其传递到src属性,以便将URL添加到src属性