Javascript selecbox.options to array?



根据我的理解,在HTML中弹出select元素的option元素是一个数组
所以基本上我想做的是返回一个用逗号分隔的数组字符串。

尝试执行selecbox.options.join(',');,但出现不支持的错误;有人知道为什么吗?

它不是一个数组。它是一个HTMLCollection。它是";类似阵列的";

2022年,在Internet Explorer 11的EOL前一周,最简单的香草JavaScript解决方案是使用排列和阵列映射

const opts = document.querySelectorAll("select option"); 
// we can use forEach on the resulting HTMLCollection 
// but map needs to be spread to array
const vals = [...opts]
  .map(el => el.value); 
console.log(vals);
<select>
<option value="Please select">Text 0</option>
<option value="one">Text 1</option>
<option value="two">Text 2</option>
<option value="three">Text 3</option>
</select><br/> 
The above select has the following option values:<br/>
<span id="result"></span>


与IE11兼容的旧答案

来自http://api.jquery.com/jQuery.each/哪一个可以迭代:

遍历对象和数组。数组和类似数组的对象length属性(例如函数的arguments对象)的迭代数字索引,从0到长度-1。其他对象通过命名属性。

每个HTML Option元素都有一个值、一个文本和一些其他属性。

可以使用简单的for循环

vals = []
var sel = document.querySelector("select");
for (var i=0, n=sel.options.length;i<n;i++) { // looping over the options
  if (sel.options[i].value) vals.push(sel.options[i].value);
}

typeracer发布的Array.apply将返回一个HTMLOptionElement数组,该数组仍需要循环或映射才能获得值和文本

以下是将返回相同的几个版本。

这个小提琴也将在IE11 中运行

var vals, sel = document.querySelector("select"), show=function(vals) {$("#result").append("[" + vals.join("][") + "]<hr/>");}
var supportsES6 = function() {try{new Function("(a = 0) => a");return true;}catch (err) {return false;  }}();

// jQuery mapping jQuery objects - note the "this" and the .get()
vals = $('select > option').map(function() {return this.value;}).get();
show(vals);
// plain JS using loop over select options
vals = [];
for (var i = 0, n = sel.options.length; i < n; i++) { // looping over the options
  if (sel.options[i].value) vals.push(sel.options[i].value); // a bit of testing never hurts
}
show(vals);
// Plain JS using map of HTMLOptionElements - note the el
vals = Array.apply(null, sel.options).map(function(el) { return el.value; });
show(vals);
// ES6 JS using spread and map of HTMLOptionElements - note the fat arrow and el
if (supportsES6) 
  document.write(`<script>
  vals = [...sel.options].map(el => el.value);
show(vals);
</script>`
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select>
<option value="Please select">Text 0</option>
<option value="one">Text 1</option>
<option value="two">Text 2</option>
<option value="three">Text 3</option>
</select><br/> 
The above select has the following option values:<br/>
<span id="result"></span>

最简洁的解决方案是:

Array.apply(null, selectbox.options)

Array.apply调用Array构造函数,第一个参数作为上下文(即this),第二个参数是任何类似数组的对象(MDN引用)。

我们为第一个参数传递null,因为我们不是试图调用特定对象上的方法,而是全局构造函数。

所以总的来说,

Array.apply(null, A)

将创建一个适当的数组,其中包含任何"类数组"对象A的元素。

将所有值放入数组:

var options = document.getElementById('selectId').options;
var values = [];
var i = 0, len = options.length;
while (i < len)
{
  values.push(options[i++].value);
}
alert(values.join(', '));

小提琴:http://jsfiddle.net/garreh/64pyb/1/


哇,做点什么还有很长的路要走

好吧,你可以使用for循环,不短得多,但更难看;

for (var options = document.getElementById('selectId').options,
          values, i = 0, len = options.length; i < len;i++)
  values.push(options[i].value);
alert(values.join(', '));

再说一遍,你没有使用像jQuery这样的库真是太遗憾了。你可以做:

$('select > option').map(function() { return this.value; }).get();

排列运算符使它非常简单([ ...ElementList ])。

因此,对于您的案例,您可以执行以下操作:
arr = document.getElementById('store-locator-region')

然后使用spread操作符将html select元素转换为对象数组:
newArr = [...arr]

然后对对象数组进行迭代,得到最终数组:
countryList = newArr.map(a => a.value)(97) ["XE", "AL", "DZ", "AD", "AR", "AM", etc..]

selecbox.options是一个集合(nodeList)。您可以像处理数组一样对其元素进行迭代,并将集合的成员推送到实际数组中。

记录在案:在除IE<9您可以使用[].slice.call(selecbox.options);1将集合快速转换为数组。

因此,将nodeList集合转换为数组的跨浏览器方法是:

function coll2array(coll){
    var ret = [];
    try {
       ret = [].slice.call(coll)
    }
    catch(e) {
        for (var i =0;i<coll.length;i++){
            ret.push(coll[i]);
        }
    }
    return ret;
}

[edit]现在(ES2015及以上)我们可以使用Array.from(options)[...options]

1Array.prototype.slice.call([some collection])

select.options不是一个数组,它是一个NodeList,它共享数组的一些功能,因此可以被描述为类似数组。NodeList没有Array所具有的方法,但您可以调用或应用这些方法。在您的情况下,您可以这样调用join方法:

var opts = yourSelect.options;
var str = Array.prototype.join.call( opts, ',' );

或者,您可以使用类似的技术将NodeList转换为真正的Array

// slice returns a new array, which is what we want
var optsArray = Array.prototype.slice.call( opts );

您可以加入一个字符串数组,但选项不是字符串,它是一个具有各种属性(如值和文本)的对象。它应该使用哪个来加入?

你只需要写一个循环来附加你想要的所有值。

或者使用一个库并使用一些each()函数来循环遍历这些选项。

我想知道为什么没有人建议这样做:

$(selecbox).find("option").map((index, option) => {
  // do stuff
});

最新更新