2012-03-09 50 views
0


我完全困惑。這是我第一個基於Javascript和jQuery的Web項目(不使用其他語言)。這是某種紡織品商店。尺寸有不同的價格。像38-43成本20,43-48成本22和48-52成本24.這就是我想要把它放在網站上的方式(38-43 => 20,43-48 => 22等)。這些文章存儲在一個XML文件,如下所示:訪問陣列索引0作品,1不是

<article id="025064"> 
    <title>Tshirt</title> 
    <desc>Description</desc> 

    <size value="38" price="50,12" /> 
    <size value="39" price="50,12" /> 
    <size value="40" price="50,12" /> 
    <size value="41" price="50,12" /> 
    <size value="42" price="50,12" /> 
    <size value="43" price="50,12" /> 
    <size value="44" price="50,12" /> 
    <size value="45" price="50,12" /> 
    <size value="46" price="50,12" /> 
    <size value="47" price="54,15" /> 
    <size value="48" price="54,15" /> 
    <size value="49" price="54,15" /> 
    <size value="50" price="54,15" /> 
    <size value="51" price="58,18" /> 
    <size value="52" price="58,18" /> 
    <size value="53" price="58,18" /> 
    <size value="54" price="58,18" /> 
</article> 

我使用jQuery來解析它。這一切都有效。現在我正在尋找價格的最低和最高尺寸。爲此,我把所有我知道的東西放在一個數組中。

var prices = new Object(); 
var laenge = 0; 

$(this).find('size').each(function(){ 
    var size = $(this).attr('value'); 
    var price = $(this).attr('price'); 

    if(typeof(prices[price])!=="undefined") 
    { 
     laenge = prices[price].length; 
    } 

    prices[price] = new Array(); 
    prices[price][laenge] = size; 
}); 

現在,我試圖通過排序陣列得到一個價格的最高和最低規模,

$.each(prices, function(index, value){ 
    prices[index].sort(); 
    var maximum = prices[index].length-1; 
    alert(prices[index][0]+" "+prices[index][maximum]); 
}); 

但我只是得到從0指數值。所有其他索引(0以上)都不起作用,即使var最大表示有幾個元素。通過使用這個下一個代碼(該代碼我以前表明內)向我表明索引被命名爲喜歡它是常規使用的是(0,1,2,3,4,5):

$.each(prices[index], function(index1, value) { 
    alert(index1); 
}); 

但我無法訪問它們。我感到很困惑。是的,我知道,我應該在下次使用Console.Log。但是,這不應該是存在的問題在這裏:)

使用的瀏覽器:谷歌瀏覽器17.0.963.66米 Web服務器(黯然):勝服務器上的IIS V6 2003標準

非常感謝你提前!

最佳,
卡爾文

+0

你可以設置索引到一個浮點數嗎?你怎麼知道它是獨一無二的?或者這很重要? – Anthony 2012-03-09 07:58:21

回答

1

0後,您將無法訪問您的示例中的任何元素,因爲你在這一行刪除任何先前的值

$(this).find('size').each(function(){ 
    ... 
    // here you erase all previous values of prices 
    prices[price] = new Array(); 
    ... 
}); 

你可以解決這個問題只創建一個新的數組,當存在沒有存在,像這樣:

var prices = {}; 
$(this).find('size').each(function() { 
    var size = $(this).attr('value'); 
    var price = $(this).attr('price'); 

    // first ensure that there is an array at prices[price] 
    // '[]' and 'new Array()' are equivalent in this case 
    prices[price] = prices[price] || [];  

    // don't hassle with the last index, simply add the size 
    prices[price].push(size); 
}); 

prices[price] || []線的字: 與C/Java不同,JavaScript中的||運算符不返回所涉及值之間的布爾比較,而是返回左側值(如果它等於true或右側值,如果左側值爲false)。因此[1,2,3] || []將返回[1,2,3],但undefined || []將返回空數組。

+0

非常感謝你的解決方案和非常理解的解釋!不勝感激!現在我懂了! – 2012-03-09 08:25:36