array + charAt issue

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]);
    }
}

This code is kind of ambiguous.

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

  • 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:

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

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


  • 假设你交出了JSON字符串的参数,然后我建议使用带有检查和JSON.parse的映射,并避免使用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; }
    链接地址: http://www.djcxy.com/p/94996.html

    上一篇: 比较不同类型的JavaScript值(不是字符串)?

    下一篇: 数组+ charAt问题