javascript,从随机字符串中获取数字数组

时间:2014-07-29 20:30:52

标签: javascript arrays

我在nums.match()上一直遇到未定义的函数错误。我也试过其他方法,但没有成功。

我想在javascript中创建一个通用函数,它将从随机字符串中提取所有数字,并按提取顺序将它们添加到数组中。任何想法为什么我一直收到这个错误?

Uncaught TypeError: undefined is not a function 

这是我目前的职能:

var nums="A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
 nums = nums.match(/\d+\.?\d*/g);

alert(nums);
var bookNums = nums.split(" ");
alert(bookNums[0],bookNums[1],bookNums[2]);

2 个答案:

答案 0 :(得分:0)

在第二行代码中赋值后,nums是一个数组而不是字符串。没有Array.prototype.split,这会导致您的错误。由于String.prototype.match返回一个数组,nums已包含您想要的值(如果未找到匹配项,则为null。)

这是一个应该有效的重写:

var nums = "A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
var bookNums = nums.match(/\d+\.?\d*/g);

console.log(bookNums);    // array or null

答案 1 :(得分:0)

var nums="A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
var nums_array = nums.match(/\d+\.?\d*/g);
var bookNums = nums_array;