以下代码输出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]);
}
}
答案 0 :(得分:0)
这段代码含糊不清。
charAt
表示将函数作为类数组对象赋予的所有参数。
String.prototype
是if (x.chatAt(0) == '[') { … }
所以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(…)) …
所以你可以做两件事:
在运行测试之前将每个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');
如果参数不是字符串,则抛出错误。要测试变量是否为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; }