如何在javascript中过滤逗号分隔的整数值

时间:2022-11-24 08:17:08

I have a varaiable in javascript like the following

我有一个像以下javascript的变量

  var element = parent.document.getElementById('productCollectionField');
  var values = element.value;

and an input field like

和输入字段

  <input type="hidden" value="1,2,3,4" id ="productCollectionField" />

so var element contains 1,2,3,4

所以var元素包含1,2,3,4

Now I have value 5 and i want to check it in values .? How can i do that...? These numbers can be anything.

现在我有值5,我想在值中检查它。我怎样才能做到这一点...?这些数字可以是任何数字。

3 个解决方案

#1


4  

var myResults = values.split(",")

You will then have an array you can parse

然后,您将拥有一个可以解析的数组

#2


3  

The simplest solution is to use the following function, which returns true of false whether the number is in the value string or not.

最简单的解决方案是使用以下函数,该函数返回true,无论数字是否在值字符串中。

var value = '1,2,3,4';

function checkNumber(number, values) {
    var numberExists = false;
    var strArray = values.split(",")

    for (var i = 0; i < strArray.length; i++)
    {
        // You could use if (strArray[i] == number), but using === is advised
        // since it's more specific about the type
        if ( parseInt(strArray[i]) === number)
            numberExists = true;
    }
    return numberExists;
}

// returns false
checkNumber(5, value);

// returns true
checkNumber(2, value);    

#3


2  

Is jQuery available to you? If yes, you can do it like this:

jQuery可以使用吗?如果是,你可以这样做:

First, what JMax said:

首先,JMax说:

var myResults = values.split(",")

Define the string that will be the output after the merge:

定义合并后将作为输出的字符串:

var newString = '';

Then,

if ( jQuery.inArray( 5, myResults ) == -1 ) {

    myResults.push( 5 );

    newString = myResults.join(',');
}

Cheers,

#1


4  

var myResults = values.split(",")

You will then have an array you can parse

然后,您将拥有一个可以解析的数组

#2


3  

The simplest solution is to use the following function, which returns true of false whether the number is in the value string or not.

最简单的解决方案是使用以下函数,该函数返回true,无论数字是否在值字符串中。

var value = '1,2,3,4';

function checkNumber(number, values) {
    var numberExists = false;
    var strArray = values.split(",")

    for (var i = 0; i < strArray.length; i++)
    {
        // You could use if (strArray[i] == number), but using === is advised
        // since it's more specific about the type
        if ( parseInt(strArray[i]) === number)
            numberExists = true;
    }
    return numberExists;
}

// returns false
checkNumber(5, value);

// returns true
checkNumber(2, value);    

#3


2  

Is jQuery available to you? If yes, you can do it like this:

jQuery可以使用吗?如果是,你可以这样做:

First, what JMax said:

首先,JMax说:

var myResults = values.split(",")

Define the string that will be the output after the merge:

定义合并后将作为输出的字符串:

var newString = '';

Then,

if ( jQuery.inArray( 5, myResults ) == -1 ) {

    myResults.push( 5 );

    newString = myResults.join(',');
}

Cheers,