以下這串json資料用來儲存預先載入的圖片路徑:
var imgData = [
{ name: "p1", src: "images/p1.jpg" },
{ name: "p2", src: "images/p2.jpg" },
{ name: "p3", src: "images/p3.jpg" },
{ name: "p4", src: "images/p4.jpg" },
{ name: "p5", src: "images/p5.jpg" }
]
下面這個函數可透過json每行的name來取得該行的路徑src,讓我們來看看程式碼:
function getData(name) {
var picArr = imgData;
var picSrc;
for (var i = 0; i
var cur_person = picArr[i];
if (cur_person.name == name) {
picSrc = cur_person.src;
}
}
return picSrc;
}
函數執行後將傳回該行的src。
var g = getData("p1");
console.log(g);
輸出後即可看到結果為:images/p1.jpg