I have some issues with my code. Here I will show two versions of my code but one of them is not working.
This code using the arguments keyword is not working:
$(document).ready(function(){
var data = {
'one':'b',
'two':'c',
'three':'d'
}
function func(){
for(var i=0;i<arguments.length;i++){
$('.a').each(function(){
if($(this).hasClass(data[arguments[i]])){
$(this).css('background','red')
}
})
}
}
func('one','two')
})
body{
margin:0;
pading:0;
height:100vh;
}
.a{
height:50px;
width:50px;
background:green;
margin:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a"></div>
<div class="a b"></div>
<div class="a c"></div>
However when I use a rest parameter, ...val, everything works perfectly:
$(document).ready(function() {
var data = {
'one': 'b',
'two': 'c',
'three': 'd'
}
function func(...val) {
for (var i = 0; i < val.length; i++) {
$('.a').each(function() {
if ($(this).hasClass(data[val[i]])) {
$(this).css('background', 'red')
}
})
}
}
func('one', 'two')
})
body {
margin: 0;
pading: 0;
height: 100vh;
}
.a {
height: 50px;
width: 50px;
background: green;
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a"></div>
<div class="a b"></div>
<div class="a c"></div>
How do I make this code work perfectly without using ...val and by using only the arguments keyword?
argumentsobject gets a new value on every function call, including the function passed to.each(). The value ofargumentsinside there is not the same as the value outside. If you used a=>function for the.each()callback, it would work, because such functions work differently in that respect.