考虑这个XML片段:
<book id="5" />
<book id="15" />
<book id="5" />
<book id="25" />
<book id="35" />
<book id="5" />
如何撰写E4X语句/查询以获取id
属性中唯一值的列表?我在JavaScript非浏览器环境中使用E4X。
5
15
25
35
是否有任何类型的distinct()
或groupby()
方法可以提供帮助?如果没有,这怎么可能实现呢?
答案 0 :(得分:2)
没有unique或groupby方法。但是,E4X允许您快速创建值非唯一值的XMLList。
var xmlSnippet = <stuff><book id="5"/>
<book id="15"/>
<book id="5"/>
<book id="25"/>
<book id="35"/>
<book id="5"/>
</stuff>;
var attributes = xmlSnippet['book'].attribute("id");
为了使其唯一,您可以获取XMLList,遍历它,并将每个元素作为键值存储在对象中。
var uniqueAttributes = new Object ();
for each (var a in attributes)
{
uniqueAttributes[a] = null;
}
要访问这些值,请使用for in循环(不是每个in)中的
进行迭代for (var u in uniqueAttributes)
{
// do something with u
}
答案 1 :(得分:1)
这假设有问题的属性值不包含管道“|”字符。如果是这样,那么将最底部的管道字符更改为不在值中的其他内容。变量是静态类型的JIT执行。希望这能满足您的需求。
var idvalues = function (x) { //x = node name
var a = document.getElementsByTagName(x),
b,
c = [],
d,
e;
for (b = a.length - 1; b > -1; b -= 1) { // gather all the id values into an array
c.push(a[b].getAttribute("id"));
}
for (b = c.length - 1; b > -1; b -= 1) {
if (c[b] !== "") {
for (d = b - 1; d > -1; d -=1) {
if (c[b] === c[d]) {
c[d] = "";
}
}
}
}
e = c.join("|");
c = e.split("|");
return c;
};