3

假设我有一个字符串“255,100,0”。如何在逗号之前隔离每个值并将其插入到 var 中?

我是说:

x = 255; y = 100; z = 0;

4

8 回答 8

2

使用 under-apppreciatedString.match()方法将返回一个包含所有匹配项的数组,按照找到的顺序排列:

var str = "255, 100, 0",
    regex = /(\d+)/g,    // g is for "global" -- returns multiple matches
    arr = str.match(regex);
console.log(arr);        // ["255","100","0"] -- an array of strings, not numbers

要将它们转换为数字,请使用一个简单的循环:

for (var i=0,j=arr.length; i<j; i++) {
    arr[i] *= 1;
};                     // arr = [255, 100, 0] -- an array of numbers, not strings
于 2013-08-14T17:04:20.630 回答
2
var str = "255, 100, 0";
var d = str.split(",");

var x = parseInt(d[0],10); // always use a radix
var y = parseInt(d[1],10);
var z = parseInt(d[2],10);

console.log(x); //255
console.log(y); //100
console.log(z); //0
于 2013-08-14T16:43:00.817 回答
1
var str = "255, 100, 0";
var str_new = str.split(",");

var x = str_new[0];
var y = str_new[1];
var z = str_new[2];
于 2013-08-14T16:43:53.627 回答
0

如果您的字符串确实众所周知/形成:

var str = "255, 100, 0";
var vals = str.split(', '); // <<= you can split on multiple chars

var x = +vals[0]; // <<= coerces to a number

// lather, rinse, repeat
于 2013-08-14T16:57:03.693 回答
0

尝试使用 JavaScript split() 方法

var str = "255, 100, 0";
var elements = str.split(','); //take values to an array
//access the elements with array index
var x = elements[0];
var y = elements[1];
var z = elements[2];

w3schools 文档在这里

于 2013-08-14T16:46:29.803 回答
0
var string = "255, 100, 0";
var arrNums = string.split(",");

将每个数字放入arrNums数组的一个元素中。

于 2013-08-14T16:44:07.143 回答
0

Have look at the Javascript split method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

var str = "255, 100, 0";
var array = str.split(',');

Then you can loop through the array and create your variables, or better use the array directly

于 2013-08-14T16:44:23.197 回答
0

Assuming you got the following string:

var string = "x = 255; y = 100; z = 0;";

You should indeed play with split function:

var values = [];
var expressions = string.split("; ");
for (var i = 0, c = expressions.length ; i < c ; i++) {
    values.push(expressions[i].split("= ").pop() * 1);
}

In expressions, you will get values like x = 255. Then, you just have to cut to the =. I just multiply it by 1 to cast it into a int.

于 2013-08-14T16:48:41.773 回答