Javascript selecbox.options 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6138042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript selecbox.options to array?
提问by Dementic
From what I understand a option
elements that popuate select
elements in HTML are an array.
So basically what i want to do is return an array string that is separated by commas.
据我了解option
,select
在 HTML 中填充元素的元素是一个数组。
所以基本上我想要做的是返回一个由逗号分隔的数组字符串。
Tried to do selecbox.options.join(',');
, but got an error that its not supported; anyone have an idea why?
试图做selecbox.options.join(',');
,但得到一个不支持的错误;有人知道为什么吗?
采纳答案by mplungjan
It is not an array. It is an object. It is "array-like"
它不是一个数组。它是一个对象。它是“阵列式”
from http://api.jquery.com/jQuery.each/which CAN iterate over either:
从http://api.jquery.com/jQuery.each/可以迭代:
Iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
迭代对象和数组。具有长度属性的数组和类数组对象(例如函数的参数对象)按数字索引进行迭代,从 0 到长度为 1。其他对象通过它们的命名属性进行迭代。
Each HTML Option elementhas a value and a text and some more attributes.
每个HTML Option 元素都有一个值和一个文本以及更多的属性。
A simple for loop can be used
可以使用一个简单的 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);
}
the Array.applyposted by typeracer will return an array of HTMLOptionElements which still needs to be looped over or mapped to get at the values and texts
该Array.apply发表typeracer将返回HTMLOptionElements数组,它仍然需要绕在或映射得到的值和文本
Here are a few versions that will return the same.
这里有几个版本会返回相同的内容。
This fiddle will run in IE11 too
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>
回答by typeracer
The most concise solution is this:
最简洁的解决方案是这样的:
Array.apply(null, selectbox.options)
Array.apply
calls the Array
constructor with the first argument as the context (i.e. this
) and the second argument which is any array-like object (MDN reference).
Array.apply
调用Array
构造函数,第一个参数作为上下文(即this
),第二个参数是任何类似数组的对象(MDN 参考)。
We pass null
for the first argument because we're not trying to call a method on a specific object, but rather a global constructor.
我们传递null
第一个参数是因为我们不是试图调用特定对象的方法,而是一个全局构造函数。
So in general,
所以一般来说,
Array.apply(null, A)
Will create a proper array containing the elements of any "array-like" object A
.
将创建一个适当的数组,其中包含任何“类数组”对象的元素A
。
回答by Gary Green
To get all the values into an array:
要将所有值放入数组中:
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(', '));
Fiddle:http://jsfiddle.net/garreh/64pyb/1/
小提琴:http : //jsfiddle.net/garreh/64pyb/1/
wow a long way to do something short
哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇
Well you can use a for loop, not much shorter but more ugly;
好吧,您可以使用 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(', '));
Then again it's a shame you're not using a library like jQuery. You could do:
再说一次,很遗憾您没有使用像 jQuery 这样的库。你可以这样做:
$('select > option').map(function() { return this.value; }).get();
回答by KooiInc
selecbox.options
is a (nodeList) collection. You can iterate over it's element like you do with an array an push the members of the collection to a real array.
selecbox.options
是一个 (nodeList) 集合。您可以像使用数组一样迭代它的元素,并将集合的成员推送到真正的数组。
For the record: in all browsers but IE<9 you can use [].slice.call(selecbox.options);
1to quickly convert a collection to an array.
记录:在除 IE<9 之外的所有浏览器中,您可以使用[].slice.call(selecbox.options);
1将集合快速转换为数组。
So a crossbrowser way to convert a nodeList collection to array would be:
因此,将 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] Nowadays (ES2015 and up) we can use Array.from([arraylike object])
.
[编辑] 如今(ES2015 及更高版本)我们可以使用Array.from([arraylike object])
.
1or Array.prototype.slice.call([some collection])
1或Array.prototype.slice.call([some collection])
回答by meouw
select.options is not an array, it is a NodeListwhich shares some of the features of an array and so can be described as array like. a NodeList doesn't have the methods that an Array has, but you can callor applythose methods to it. In your case you can call the join method like this:
select.options 不是数组,它是一个NodeList,它共享数组的一些特性,因此可以描述为类似数组。NodeList 没有 Array 具有的方法,但您可以对其调用或应用这些方法。在您的情况下,您可以像这样调用 join 方法:
var opts = yourSelect.options;
var str = Array.prototype.join.call( opts, ',' );
Alternatively you could convert the NodeList into a true Array with a similar technique
或者,您可以使用类似的技术将 NodeList 转换为真正的 Array
// slice returns a new array, which is what we want
var optsArray = Array.prototype.slice.call( opts );
回答by edwin
You can join an array of strings, but an option is not a string, it's an object with all kinds of properties like value and text. Which should it use to join?
您可以连接字符串数组,但选项不是字符串,它是具有各种属性(如值和文本)的对象。它应该使用哪个加入?
You just have to write a loop to append all values you want.
您只需要编写一个循环来附加您想要的所有值。
Or use a library and use some each() function to loop through the options.
或者使用库并使用一些 each() 函数来循环选项。
回答by Heshie Brody
The spread operatormakes it really easy ([ ...ElementList ]
).
So for your case you can do the following:
arr = document.getElementById('store-locator-region')
Then convert the html select element to an object array using the spread operator:
newArr = [...arr]
And then iterate over your object array to get your final array:
countryList = newArr.map(a => a.value)
(97)?["XE", "AL", "DZ", "AD", "AR", "AM", etc..]
该价差操作变得非常简单([ ...ElementList ]
)。
因此,对于您的情况,您可以执行以下操作:
arr = document.getElementById('store-locator-region')
然后使用扩展运算符将 html select 元素转换为对象数组:
newArr = [...arr]
然后迭代您的对象数组以获得最终数组:
countryList = newArr.map(a => a.value)
(97)?["XE", "AL", "DZ", "AD", "AR", "AM", etc..]