array + charAt问题

时间:2017-05-11 06:07:47

标签: javascript arrays

以下代码输出k[i].charAt is not a function错误。奇怪的是,没有错误 - 结果是正确的 - 如果不是i我放了一个数字k[1].charAt(0)。与indexOf相同。

for (i = 0; n < arguments.length; i++) {
    k[i] = arguments[i];
    if (k[i].charAt(0) == "["){
        k[i] = eval(k[i]);
    }
}

2 个答案:

答案 0 :(得分:0)

这段代码含糊不清。

  1. charAt表示将函数作为类数组对象赋予的所有参数。

  2. String.prototypeif (x.chatAt(0) == '[') { … }

  3. 上定义的函数

    所以x仅在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 为String时才有效,否则您将获得上述错误。

    总而言之(在es6中):

    if (''+ arg.charAt(…)) …

    所以你可以做两件事:

    1. 在运行测试之前将每个arg转换为字符串:if (arg.toString().charAt())// Or the encoding of the file var encoding = Encoding.GetEncoding("iso-8859-1"); // where somefile.txt is your file string text = File.ReadAllText("somefile.txt", encoding); // the splitted parts. FS is the \x1C hex character. string[] parts = text.Split('\x1C');

    2. 如果参数不是字符串,则抛出错误。要测试变量是否为String,可以找到here

答案 1 :(得分:0)

假设您移交了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; }

相关问题