0

如何动态添加数组,如下面的代码所示。我已经在 J​​avaScript 中创建了一个多维数组,但是我该如何推送src"/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg"title那是"MyTitle". 我有多个值,我正在遍历它们?

carousel_images_info = [
    { src: "/_layouts/15/My.Portal/Images/my1.jpg", title: "ssnit01" },
    { src: "/_layouts/15/my3.Portal/Images/my2.jpg", title: "ssnit02" },
    { src: "/_layouts/15/my4.Portal/Images/my3.jpg", title: "ssnit03" },
    { src: "/_layouts/15/my5.Portal/Images/my4.jpg", title: "ssnit04" },
    { src: "/_layouts/15/my5.Portal/Images/ssnit05.jpg", title: "ssnit05" }
];
4

4 回答 4

1

只是推:)

carousel_images_info.push({ 
    title: "MyTitle",
    src: "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg"
});

但是,如果您想避免重复,则必须在添加新行之前遍历整个列表以执行比较。另一种解决方案可能是推送所有内容,然后仅在需要时删除重复项。

于 2013-09-05T09:00:51.127 回答
1

那是包含对象的数组,您需要将对象推送到它,例如:

var new_obj = {
    src: "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg",
    title: "My Title"
};
carousel_images_info.push(new_obj);
于 2013-09-05T09:01:19.550 回答
0

src 和 title 的值是动态的,所以我可以这样做吗?

  var item_enumerator = this.items.getEnumerator();
  while (item_enumerator.moveNext()) {
    var item = item_enumerator.get_current();
    var image_url = location.protocol + "//" + location.host + item.get_item('FileRef');
    var image_title = item.get_item('FileLeafRef'); 
    var set = {
      src: image_url,
      title : image_title
    };
    this.carousel_images_info.push(set);
  }
于 2013-09-05T09:10:53.470 回答
0

试试这个,

var new_obj = {};
new_obj.src = "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg";
new_obj.title= "MyTitle";

carousel_images_info[carousel_images_info.length] = new_obj

因此,如果您要动态执行此操作,请创建一个函数,

carousel_images_info=[];

function Insert(xSrc,xTitle)
{
    var new_obj = {};
    new_obj.src = xSrc;
    new_obj.title= xTitle;

    carousel_images_info[carousel_images_info.length] = new_obj;
}

Insert("/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg","MyTitle");
于 2013-09-05T09:20:33.683 回答