I’m learning javascript and can’t figure out the problem in my code below. I guess I misunderstand how arrays actually work.
The problem is that the alerted array is not actually sorted. I would be grateful for any insights on this:
HTML:
<html>
<head>
<title>
Test 1
</title>
<script src="http://code.jquery.com/jquery-latest.js" type=
"text/javascript">
</script>
</head>
<body>
<div class="items">
<ul>
<li>
<a href="#" id="1">Link 1</a>
</li>
<li>
<a href="#" id="2">Link 2</a>
</li>
<li>
<a href="#" id="3">Link 3</a>
</li>
<li>
<a href="#" id="4">Link 4</a>
</li>
</ul>
</div>
</body>
</html>
Javascript:
var clickedLinks = [];
var passedItems = [];
// Collect clicked link IDs into an array and pass the array as an argument to shoplist()
$('.items a').click(function () {
if (clickedLinks.indexOf(this.id) != -1) {
var linkIndex = clickedLinks.indexOf(this.id);
clickedLinks.splice(linkIndex, 1);
} else {
clickedLinks.push(this.id);
}
shoplist(clickedLinks);
});
function shoplist(ids) {
passedItems.push(ids.slice());
alert(passedItems.sort());
}
Steps to reproduce:
- Click Link 2
- Click Link 1
Expected Result: 1, 2, 2
Actual Result: 2, 2, 1
Things I’ve tried:
function shoplist(ids) {
passedItems.push(ids.slice());
var newpi = passedItems.slice();
alert(newpi.sort());
}
You are adding an array, the result of
ids.slice(), to another array. That’s why the sort doesn’t work as you expect. Useconcatinstead, if you want to add the contents ofidsto thepassedItemsarray:Also, instead of adding a string to the
idsarray, you should use.push(parseInt(this.id))instead, and then use: