0

I've created a function that takes in a variable and returns the last value in the variables array. How do I push multiple variables arrays to go through the function? It works for var arr but not pzz?

var arr = ['abc', 'def', 'ghi'];
var pzz = ['jkl', 'lmn', 'opq'];
    
      
    function valueIn(v) {
        vLength = v.length;
    
        console.log(v[vLength-1]);
    
    }

    
valueIn(arr);

5
  • 1
    [arr, pzz].forEach(valueIn) Commented May 2, 2018 at 1:07
  • Thanks works great. Just out of interest is there a way to loop through the script to identify all the declared variables in the global scope? Commented May 2, 2018 at 1:11
  • Ideally, you shouldn't have any variables in the global scope except for the built-in ones. If you want to iterate over a bunch of variables, then just assign them to an array in advance. const myArrs = [arr, pzz]; Commented May 2, 2018 at 1:12
  • try this valueIn([...arr,...pzz]) Commented May 2, 2018 at 1:16
  • @NS01 Especially, you shouldn’t have any unknown variable names. If you want dynamic names, use an object instead: let obj = {arr, pzz}, then get obj.arr, or use one of the Object methods to iterate through them. Commented May 2, 2018 at 1:19

2 Answers 2

1

One way to do this is to use the js Arguments object to access every argument sent. reference.

var arr = ['abc', 'def', 'ghi'];
var pzz = ['jkl', 'lmn', 'opq'];
    
function valueIn() {
   for (i = 0; i < arguments.length; i++) {
      v = arguments[i];
      console.log(v[v.length - 1]);
   }
}
   
valueIn(arr, pzz);

A second way to do this is to use the spread operator. reference.

var arr = ['abc', 'def', 'ghi'];
var pzz = ['jkl', 'lmn', 'opq'];
    
function valueIn(...args) {
   for (i = 0; i < args.length; i++) {
      v = args[i];
      console.log(v[v.length - 1]);
   }
}
   
valueIn(arr, pzz);

Sign up to request clarification or add additional context in comments.

Comments

1

The following code assumes your intent is to write to the console. @CertainPerformance is correct to recommend to run a for each loop. However, I would recommend pushing the values to another array so you can run it as needed.

var valueInArray = [];
var arr = ['abc', 'def', 'ghi'];
var pzz = ['jkl', 'lmn', 'opq'];
valueInArray.push(arr, pzz);

function valueIn(v) {
  vLength = v.length;

  console.log(v[vLength - 1]);

}


valueInArray.forEach(function(el) {
  valueIn(el);
});

And in ES6

var valueInArray = [];
var arr = ['abc', 'def', 'ghi'];
var pzz = ['jkl', 'lmn', 'opq'];
valueInArray.push(arr, pzz);

function valueIn(v) {
  vLength = v.length;

  console.log(v[vLength - 1]);

}


valueInArray.forEach(el => (valueIn(el)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.