Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active November 14, 2017 23:13
Show Gist options
  • Save aderaaij/0f04b1e3599b8bc061ea926c54a243ba to your computer and use it in GitHub Desktop.
Save aderaaij/0f04b1e3599b8bc061ea926c54a243ba to your computer and use it in GitHub Desktop.
There are several occasions where you get an array-like value, which isn't actually an array. The most common occasion is when you do `document.querySelectorAll()`, which returns a nodelist instead of an Array. Another possibility is when you use a function which takes in multiple arguments, and you use the `arguments` keyword to retrieve those.…
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array .from()</title>
</head>
<body>
<ul class="heroes">
<li>Hulk</li>
<li>Thor</li>
<li>Iron Man</li>
<li>Vision</li>
<li>Misty Knight</li>
<li>Jessica Jones</li>
<li>The Punisher</li>
</ul>
<script>
// Array.from takes in a function as a second argument, so you can directly return
// a value:
const heroNodes = document.querySelectorAll('li');
const heroes = Array.from(heroNodes, hero => hero.textContent);
console.log(heroes);
// Other ways to turn a nodelist into an array:
console.log(Array.prototype.slice.call(document.querySelectorAll('li')));
// Using the ES6 spread operator
console.log([...document.querySelectorAll('li')]);
// Using Array.from to turn an arguments object into an array
function sumAll() {
const nums = Array.from(arguments);
console.log(nums);
return nums.reduce((a, b) => a + b);
}
sumAll(2, 34, 23, 234, 234, 234234, 234234, 2342);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment