Reputation: 41
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?
Upvotes: 3
Views: 231
Reputation: 451
Try using a local var inside func():
$(document).ready(function(){
var data = {
'one':'b',
'two':'c',
'three':'d'
}
function func(){
for(var i=0;i<arguments.length;i++){
var key = arguments[i]
$('.a').each(function(){
if($(this).hasClass(data[key])){
$(this).css('background','red')
}
})
}
}
func('one','two')
})
In the original posted form, the nested anonymous function was referring to its own arguments, but the intent (as I interpreted it) was to refer to the arguments of the call to func() instead. As it was pointed out by others, that is not possible since the arguments keyword is always local to the current function. Therefore by adding a var to the closure (inside func() but outside of the nested anonomous function) you can refer to that "copy" of the data in the outer arguments instead when inside the nested function.
Upvotes: 1
Reputation: 33
There are two more possible ways to do this in addition to your way:
Upvotes: 2
Reputation:
You need to use input parameter (...val
in your case).
Every time you call your method you pass a new parameter in it.
Upvotes: 0
Reputation: 129
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.
Upvotes: 3