Javascript 访问数组索引0有效,1无效

Javascript 访问数组索引0有效,1无效,javascript,jquery,Javascript,Jquery,我完全糊涂了。这是我第一个基于Javascript和jQuery的web项目(没有使用其他语言)。这是一家纺织店。不同的尺码有不同的价格。像38-43需要20美元,43-48需要22美元,48-52需要24美元。这就是我想把它放到网站上的方式(38-43=>20,43-48=>22,等等)。文章存储在xml文件中,如下所示: <article id="025064"> <title>Tshirt</title> <desc>Desc


我完全糊涂了。这是我第一个基于Javascript和jQuery的web项目(没有使用其他语言)。这是一家纺织店。不同的尺码有不同的价格。像38-43需要20美元,43-48需要22美元,48-52需要24美元。这就是我想把它放到网站上的方式(38-43=>20,43-48=>22,等等)。文章存储在xml文件中,如下所示:

<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>
现在我试图通过对数组进行排序来获得价格的最高和最低大小

$.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)类似:

但我无法访问它们。我很困惑。是的,我知道,我应该使用控制台。下次登录。但这不应该是问题:)

使用过的浏览器:Google Chrome 17.0.963.66 m Web服务器(很遗憾):win server 2003标准上的IIS v6

提前非常感谢

最佳,

Calvin

在您的示例中,您不能访问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]
,但是
未定义的| |【】
将返回空数组。

可以将索引设置为浮点吗?你怎么知道它是否独一无二?或者这有关系吗?非常感谢您提供的解决方案以及对此的非常易懂的解释!谢谢!现在我明白了!
$(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);
});