以下這串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 < picArr.length; 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