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

Reading values with different datatypes inside a string in javascript

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

以下应该适用于任意数量的参数。

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

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

foo(...args);

您对 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(',')来根据逗号字符[=22=分割字符串].

" 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);