0

The following code output a k[i].charAt is not a function error. The strange thing is that there is no error - and the result is correct - if instead of i I put a number k[1].charAt(0). Same thing with indexOf.

for (i = 0; n < arguments.length; i++) {
    k[i] = arguments[i];
    if (k[i].charAt(0) == "["){
        k[i] = eval(k[i]);
    }
}
tanmay
  • 7,761
  • 2
  • 19
  • 38

2 Answers2

0

This code is kind of ambiguous.

  1. arguments represents all arguments given to a function as array-like object.

  2. charAt is a function defined on String.prototype

So if (x.chatAt(0) == '[') { … } will only work if x is a String, otherwise you will get the Error as described above.

All in all (in es6):

const foo = (...args) => {
  for (let arg of args) {
    if (arg.chatAt(0) == '[') { … }
  }
} 

foo({}) // Error
foo('[', {}) // Error, because arg2 is not a string
foo('[', ']') // No Errors, because each arg is a String

So there are two things you could do:

  1. convert each arg to a string, before running the test: if (''+ arg.charAt(…)) …, or if (arg.toString().charAt())

  2. throw an Error if an Argument is not a string. To test if a variable is a String can be found here

Community
  • 1
  • 1
philipp
  • 15,947
  • 15
  • 61
  • 106
0

Assuming, you hand over arguments, which are JSON strings, then I suggest to use a mapping with a check and JSON.parse and avoid to use eval.

function convert() {
    return Array.prototype.map.call(arguments, function (a) {
        return a[0] === '[' ? JSON.parse(a) : a;
    });
}

console.log(convert('a', 1, '[1,2,3]'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392