从一个特定的INPUT Javascript获取数字

Get numbers from a specific INPUT Javascript

本文关键字:INPUT Javascript 获取 数字 一个      更新时间:2023-09-26

嗯,我的问题是我需要获得特定链的值。case存储在变量_INPUT

第一行包含T,测试用例的数量。接下来是T测试用例,每个用例在一个新的行中。每个测试用例包含两个空格分隔的整数,分别表示A和b。

_INPUT = "2'n3 9'n17 24";

输入值的方式是:cont_sqrt(3,9);但是我的老师不希望这样。我的函数是

 `function cont_sqrt(a,b){
positives=0;  
for(x=a;x<=b;x++){
sqrtmath=Math.sqrt(x); 
if(sqrtmath % 1 ==0){
positives++;
}
}
console.log(positives);
}`

您可以使用isNumeric()

var input = "2'n3 9'n17 24";
var inputSplit = input.split('');
alert(inputSplit);
var arr = [];
$.each(inputSplit,function(i,val){     
    if ($.isNumeric(val)) {
        arr.push(val);
    }
});
 alert(arr);

JSFiddle

假设这将是您的_INPUT字符串的一致结构,这就是您可以做到的。

var _i = _INPUT.split(''n');
var T = _i[0]; // gives you 2
for(var i=1;i<_i.length;i++){
    var current = _i[i].split(' ');
    var _A = current[0];//Gives you 3 in first iteration and 17 in 2nd iteration and so on
    var _B = current[1]; //Gives you 9 in first iteration and 24 in 2nd iteration.
}

假设传递的初始数字是将要出现的情况的数量,您可以这样做:

var _INPUT = "2'n3 9'n17 24";
var inputParts = _INPUT.split(/'n/);
var caseAmount = inputParts[0];
var cases = inputParts[1].split(/'s/);
var casesInt = inputParts[2].split(/'s/);
var result = {};
result['size'] = caseAmount;
result['cases'] = [];
for(var index = 0; index < caseAmount; index ++){
    result['cases'][index] = {'case' : cases[index], 'caseInt' : casesInt[index]};
}
console.log(result);
输出:

Object
    cases: Array[2]
        0: Object
            case: "3"
            caseInt: "17"
            __proto__: Object
        1: Object
            case: "9"
            caseInt: "24"
            __proto__: Object
        length: 2
        __proto__: Array[0]
    size: "2"
__proto__: Object