2011-10-20 14 views
2

這是一個非常簡單的問題,但我無法弄清楚我做錯了什麼。假設我有這個對象:遍歷JavaScript對象 - 我錯過了什麼?

features: { 
    savings: { 
     link: "test.html", 
     img: "/_assets/img/related-content/sample.png" 
    }, 
    security: { 
     link: "test2.html", 
     img: "/_assets/img/related-content/sample2.png" 
    }, 
    speed: { 
     link: "test3.html", 
     img: "/_assets/img/related-content/sample3.png" 
    } 
} 

假設這種格式已設置且無法更改。我可以很容易地通過做類似features["savings"].link的選擇。但是,讓我們說我想從這個對象中獲得一個隨機項目。我會生成一個隨機數,然後使用它選擇索引。但features[randnum].link不起作用。爲什麼是這樣?我如何在不修改對象格式的情況下做到這一點?

謝謝!

+0

糟糕,改變標題。 –

+1

[從Javascript對象中挑選隨機屬性]的可能重複(http://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object) –

+0

謝謝,這個鏈接回答了我的問題。 –

回答

3

這是因爲你在處理一個對象而不是數組,所以你不能用一個數字來索引對象。你將不得不做這樣的事情:

var randnum = getRandomNumber(1, 3); // get random num between 1 and 3 
var randomLink = features["feature" + randnum].link; 

只是爲了澄清,這個符號:

features["feature1"].link; 

相同

features.feature1.link; 

如果沒有屬性名稱,你可以像「安全」或「儲蓄」一樣輕鬆生成,假設屬性是靜態的,則可以使用數組來幫助您。

var properties = [ "security", "savings" ]; 
var randomProperty = properties[Math.floor(Math.random() * properties.length)]; 
var randomLink = features[randomProperty].link; 

如果你不知道你是什麼性質將是,那麼你就可以收集他們:

var properties = []; 
for (var prop in features) { 
    if (features.hasOwnProperty(prop)) { 
     properties.push(prop); 
    } 
} 
var randomProperty = properties[Math.floor(Math.random() * properties.length)]; 
var randomLink = features[randomProperty].link; 
+0

假設我只有類別名稱(如安全性,儲蓄等)而不是feature1,feature2等。那我該怎麼做呢? –

+1

@ellenchristine:你可以獲得數組中的所有鍵和[隨機選擇一個元素](http://stackoverflow.com/questions/4550505/javascript-getting-random-value-from-an-array)。 –

+0

@ellenchristine:我爲你更新了答案。 –

0

JS對象不numericaly索引,你不能訪問它作爲使用整數的數組。

+0

。所以我只能把它當作一個關聯數組呢? –

+0

雖然它不是一個關聯數組,但它是一個對象。語法'myArray ['myPropertyName']'是訪問對象屬性的一種不同方式。 –

+0

你不能說他們沒有數字索引。我認爲從某種意義上說,如果它們不是聯想的,那麼所有數組都是。無論如何..以W3爲例,他們在那裏顯示一個索引數組。而且我知道我曾經在對象/數組中使用過myobj [0] .myproperty。 W3 ref:http://www.w3schools.com/js/js_obj_array.asp – chris

0

對你的原始json結構的特性[something]會使它尋找features.something。但是,您實際上可以使特性成爲一個json對象數組。這會給你你想要的隨機訪問。然而,除非你想到創建數組,否則它會成爲一個'搜索'功能來查找feature3。

爲特徵[randomInteger]。鏈路,改變下面的結構:

var features = [{ 
     name:"feature1", 
     link: "test.html", 
     img: "/_assets/img/related-content/sample.png" 
    }, 
    { 
     name:"feature2", 
     link: "test2.html", 
     img: "/_assets/img/related-content/sample2.png" 
    }, 
    { 
     name:"feature3", 
     link: "test3.html", 
     img: "/_assets/img/related-content/sample3.png" 
    }]