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?
This is because 'arguments' is a reserved keyword in Javascript. It's context will change when you call it inside other function inside the .each(). It is not just like any other variable that will be passed inside as it is.
If you want to achieve that, you should use arrow functions.
Arrow functions in JS
Hope that the issue was fixed.
There are two more possible ways to do this in addition to your way:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With