获取HTMLCollection的特定属性



所以我想知道是否有一种方法可以获得例如HTMLCollection的所有value's。像这样:

var users = document.getElementsByName('users')
var userLength = []
for (var i = 0; i < users.length; i++) {
userLength.push(users[i].value);
}
userLength.sort(function(a, b){return b - a});
console.log(userLength);

…但是在一行中,更像这样:

document.getElementsByName('users').value

如果您想运行这个,它是为stackexchange上的sites-section编写的。不,第二个不行

我不会使用jQuery,所以这不是我的选择。

首先使用Spread syntax (...)获取元素数组,然后使用Array.prototype.map()获取所有值。最后,在返回的结果上链接sort方法:

var users = document.getElementsByName('users')
var userLength = [...users].map(el => +el.value).sort(function(a, b){return b - a});
console.log(userLength);
<input name="users" value="11"/>
<input name="users" value="22"/>

最新更新