据我了解,填充 HTML 中
option
元素的 select
元素是一个数组。尝试做
selecbox.options.join(',');
,但得到了不支持的错误;有人知道为什么吗?
它不是一个数组。它是一个 HTMLCollection。它是“类似数组”
2022 年,即 Internet Explorer 11 停产前一周,最简单的 JavaScript 解决方案是使用 spread 和 Array map
更新:Array.from实际上比传播更可取,因为它更明显发生了什么
const opts = document.querySelectorAll("select option");
// we can use forEach on the resulting HTMLCollection
// but map needs to be spread to array
const vals = Array.from(opts) // or [...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 属性(例如函数的 参数对象)被迭代 数字索引,从 0 到 length-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 将返回一个 HTMLOptionElements 数组,该数组仍然需要循环或映射才能获取值和文本
这里有几个版本会返回相同的结果。
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')
newArr = [...arr]
countryList = newArr.map(a => a.value)
(97) ["XE", "AL", "DZ", "AD", "AR", "AM", etc..]
selecbox.options
是一个集合(nodeList
)。您可以像处理数组一样迭代其元素,并将集合的成员推送到真正的数组中。
郑重声明:在除 IE 之外的所有浏览器中<9 you can use
[].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]
。
1 或
Array.prototype.slice.call([some collection])
select.options 不是一个数组,它是一个 NodeList,它共享数组的一些功能,因此可以被描述为类似数组。 NodeList 没有 Array 所具有的方法,但您可以 call 或 apply 对其使用这些方法。 在你的情况下,你可以像这样调用 join 方法:
var opts = yourSelect.options;
var str = Array.prototype.join.call( opts, ',' );
或者,您可以使用类似的技术将 NodeList 转换为真正的数组
// 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
});