$=jQuery.noConflict();
$( document ).ready(function() {
//returns an array of image links
// ["http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-1-150x150.jpg", "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file9221293737060-150x150.jpg", "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"]
var images = <?php echo json_encode($images); ?>;
console.log(images);
src = [];
data = {}
for (var i = 0; i < images.length; i++) {
data = {
src: images[i]
};
src.push(data);
console.log(data);
//Data should equal [{src : imageurlxxx}, {src :imgurlxxdd}, {src :imgurlxxdd} ]}
}
});//close
上面的代码应循环遍历images数组并将其推入以src
为键的对象,然后将该对象推入数组并重复。问题是该对象在数组中被覆盖,因为它们都具有相同的密钥。
答案 0 :(得分:4)
您的代码完全符合您的要求,但您检查了错误的变量:
var images = ["A", "B", "C"]
console.log(images);
src = [];
data = {}
for (var i = 0; i < images.length; i++) {
data = {
src: images[i]
};
// Here data is an object with 1 key only.
src.push(data);
}
// Here - after the loop - the src variable will contain all of the values that you want.
console.log(src);
如果您正在寻找ES6解决方案,您可以使用此解决方案:
var images = ["A", "B", "C"];
var src = images.map((img) => { return {src: img} });
console.log(src);
答案 1 :(得分:1)
function getImages() {
var images = <?php echo json_encode($images); ?>;
return images.map(function (image) {
return { src: image };
}
};
假设你在php网站上使用它并设置了$ images,getImages()会返回如下内容:
[
{src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"},
{src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file9221293737060-150x150.jpg"},
{src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"}
]
答案 2 :(得分:0)
//Data should equal [{src : imageurlxxx}, {src :imgurlxxdd}, {src :imgurlxxdd} ]}
data = $.map(images, (image) => { src: image })
如果我正在阅读你想要的内容,你只需要将你的图片网址映射到你想要的数组中。