Javascript - 循环遍历数组

标签 javascript jquery arrays node.js mongoose

概述:我需要使用任何新图像链接来更新包含图像链接的数组。同时,我将所有以前上传的图像保留在数组中。我的问题是,在执行此操作时,之前的图像链接会合并。下面的例子。我将如何更改代码来修复数组?感谢您的帮助。

    var allimages = []

    var allCurrentImages = req.body.oldimages
    //this pulls all the previous image links

        if (allCurrentImages && allCurrentImages.length > 2){
         for (i=0;i<allCurrentImages.length;i++){
         allimages.push(allCurrentImages[i]);
         }
    }

    if (filepath && filepath.length > 2){
    allimages.push(filepath);
    }

问题

问题就在这里。如果 var allCurrentImages 中有两个图像,则数组会将它们合并为一项,因为我正在请求正文。当有 3 个图像时,它看起来像这样:

images[0] =  uploads/598f4cc,uploads/53eew2w
images[1] =  uploads/7wusjw2w

它需要看起来像这样:

images[0] = uploads/598f4cc
images[1] = uploads/53eew2w
images[2] = uploads/7wusjw2w

所以我需要以某种方式将 req.body.oldimages 分成单独的部分,然后再将其推送到数组。 (我认为。)非常感谢任何帮助或建议!

最佳答案

您可以先将其拆分:

var allCurrentImagesTmp = req.body.oldimages
var allCurrentImages = [];

for (i=0;i<allCurrentImagesTmp .length;i++){
  allCurrentImages.concat(allCurrentImagesTmp[i].split(","));
}
...
// your code

关于Javascript - 循环遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45683438/

相关文章:

javascript - 按数字偏移数组值,用于在 Bootstrap 列上重复 ng

Javascript 和 jQuery 数组未定义

javascript - 如何将window.onload附加到jquery中的特定页面

java - 如何计算 print 语句中 int 数组的平均值? (java)

javascript - 将数组对象展平为单个对象 - Javascript

javascript - JQuery:验证表单中的所有输入

javascript - 当缓存 Assets 的查询字符串参数更改时,Akamai 是否从源中提取

javascript - React Navigation Bottom TabBar 图标间距

javascript - 单击模式提交按钮后打开警报窗口

c# - 计算字节数组中位和的最快方法