我是javascript新手。我想从集合容器中获取特定元素。 这是我的源代码:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + setObj1.values[1];
<div id="demo"> </div>
<div id="demo1"> </div>
请更正我的语法或建议我使用一种方法来打印set的特定索引值。
答案 0 :(得分:3)
您可以这样做
var i, item,val = '';
var setObj1 = new Set();
for(i=0;i<5;i++){
setObj1.add(i);
}
for (item of setObj1.values()){
val+=item + ' ';
}
var iterator = setObj1.values();
iterator.next();
document.getElementById('demo').textContent = "The set values are: "+val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: "+ iterator.next().value;
注意:如果要获取带有索引的值,最好使用数组而不是Set
答案 1 :(得分:2)
尽管您可以做到这一点,但这很昂贵。集合不适用于面向索引或面向键的操作(为此使用数组或Map)。
昂贵的方法是将集合转换为数组(通过集合的迭代器间接使用values
并从头到尾进行迭代以获得完整集合)并索引到数组中:
document.getElementById('demo1').innerHTML = [...setObj1][1];
实时示例:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + [...setObj1][1];
<div id="demo"> </div>
<div id="demo1"> </div>
但这是您使用数组的示例:
var i, item, val = '';
var values = [];
for (i = 0; i < 5; i++) {
values[i] = i;
}
document.getElementById('demo').textContent = "The set values are: " + values.join(" ");
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + values[1];
<div id="demo"> </div>
<div id="demo1"> </div>