在JavaScript中的字符串中读取具有不同数据类型的值

时间:2018-11-16 10:14:42

标签: javascript string eval

假设我有一个字符串 var str = " 1, 'hello' " 我正在尝试为函数提供以上在str中找到的值,但应使用整数和字符串-而不是一个字符串- 例如myFunc(1,'hello') 我该怎么做到 我尝试使用eval(str), 但我得到invalid token , 我该如何解决?

2 个答案:

答案 0 :(得分:0)

以下内容适用于任意数量的参数。

function foo(num, str) {
  console.log(num, str);
}

const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');

foo(...args);

答案 1 :(得分:0)

使用eval(str)时,您几乎有了正确的主意,但这并不是您真正想要评估的东西。如果您确实使用eval(str),则与说eval(" 1, 'hello' ")

相同

但是,您真正想要做的是: eval("func(1, 'hello world'))

为此,您可以执行以下操作:

eval(func.name + '(' + str.trim() + ')');

这里有:

  • func.name:要调用的函数的名称。您当然可以对此进行硬编码。 (即只写“ func(” + ...)

  • str.trim():要传递给给定函数的参数。在这里,我还使用.trim()删除了字符串周围的任何其他空格。

看看下面的代码片段。在这里,我基本上写出了上面的代码行,但是,我使用了一些中间变量来帮助阐明其工作原理:

function func(myNum, myStr) {
  console.log(myNum*2, myStr);
}

let str = " 1, 'hello, world'";


// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';

eval(fncStr);

或者,如果只希望传递两个参数,则可以在字符串上使用.split(','),以根据逗号字符,分割字符串。

" 1, 'hello' "上使用split将给您一个像这样的数组a

let a = [" 1", "'hello'"];

然后将您的字符串转换为整数,并使用.replace(/'/g, '');删除字符串周围的其他引号(将所有'引号替换为''

let numb = +a[0].trim(); // Get the number (convert it to integer using +)

let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()

现在您可以使用以下两个变量来调用函数:

func(numb, str);

function func(myNum, myStr) {
  console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}

let arguments = " 1, 'hello' ";
let arr = arguments.split(',');

let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2

func(numb, str);