javascript - Convert string to array - jQuery.inArray() not working - Stack Overflow

I have a string that looks like this (this is a value I get from an input in the page's HTML):

I have a string that looks like this (this is a value I get from an input in the page's HTML):

'[123,234,345]'

I turn this value into an array in my JS:

var tempProjectTasks = $('#task_id_array').val();
tempProjectTasks = tempProjectTasks.replace('[', '').replace(']','');
selectedProjectTasks = tempProjectTasks.split(',');

I then pare this array in a loop

$.each(tasks, function(key, value) {
    if ($.inArray(value['id'], selectedProjectTasks) != -1) {
        checked = 'checked';
    } else {
        checked = '';
    }
    ... more stuff here ...
});

This is building a list for the HTML and each row contains a checkbox.

I can see in the console the parison for these values being -1 by adding the console.log mands below inside the loop.

console.log(selectedProjectTasks);
console.log(value['id']);
console.log($.inArray(value['id'], selectedProjectTasks));

In the console:

["123","234","345"]
123
-1

Why is the inArray() not finding the matching values? What have I missed? Thanks

I have a string that looks like this (this is a value I get from an input in the page's HTML):

'[123,234,345]'

I turn this value into an array in my JS:

var tempProjectTasks = $('#task_id_array').val();
tempProjectTasks = tempProjectTasks.replace('[', '').replace(']','');
selectedProjectTasks = tempProjectTasks.split(',');

I then pare this array in a loop

$.each(tasks, function(key, value) {
    if ($.inArray(value['id'], selectedProjectTasks) != -1) {
        checked = 'checked';
    } else {
        checked = '';
    }
    ... more stuff here ...
});

This is building a list for the HTML and each row contains a checkbox.

I can see in the console the parison for these values being -1 by adding the console.log mands below inside the loop.

console.log(selectedProjectTasks);
console.log(value['id']);
console.log($.inArray(value['id'], selectedProjectTasks));

In the console:

["123","234","345"]
123
-1

Why is the inArray() not finding the matching values? What have I missed? Thanks

Share Improve this question asked Sep 4, 2016 at 6:52 TheRealPapaTheRealPapa 4,5399 gold badges80 silver badges165 bronze badges 2
  • What is value['id']? Is it a badly formed array or an object? – zer00ne Commented Sep 4, 2016 at 6:58
  • maybe you should try using parseInt() on value['id'] – thephpx Commented Sep 4, 2016 at 7:01
Add a ment  | 

5 Answers 5

Reset to default 4

["123","234","345"] is an array of string, where as 123 is an integer.

You can convert this to string using toString before searching it in array

console.log($.inArray((value['id'].toString(), selectedProjectTasks));

I believe the answer lies in the $.inArray() docs, where it says

The parison between values is strict. The following will return -1 (not found) because a number is being searched in an array of strings

You should either convert your new array to numbers or your pared value to a string. Then it should work.

I was paring string elements to integers so inArray() was failing.

I just added the following line and voila!

var tempProjectTasks = $('#task_id_array').val();
tempProjectTasks = tempProjectTasks.replace('[', '').replace(']','');
selectedProjectTasks = tempProjectTasks.split(',');
for(var i = 0; i < selectedProjectTasks.length; i++) selectedProjectTasks[i] = +selectedProjectTasks[i];

Hope this helps someone else. Thanks.

You can do like this one

var arrStr = str.replace(']','').replace('[','').split(",")
arrStr = arrStr.map(Number);
$.inArray(123,arrStr);

You can do it without jQuery function using JavaSscript#indexOf.

var arrStr = str.replace(']','').replace('[','').split(",")
arrStr = arrStr.map(Number);
arrStr.indexOf(value['id']);
 // return -1 id no find otherwise return index of the element.

The problem is that the parision that inArray() does is strict. You can use $.grep() instead.

RegularExpression specific approach.

var strArray = '[123,234,345]';
var selectedProjectTasks = (/^\[(.*)\]$/g.exec(strArray)[1]).split(",")

console.log(selectedProjectTasks[0], selectedProjectTasks[1], selectedProjectTasks[2]);

//then you can do your parisions
var value = [], checked;
value['id'] = 123;

if (($.grep(selectedProjectTasks, function(n) { return n == value['id']; })) != '[]') {
    checked = 'checked';
} else {
    checked = '';
}

console.log(checked);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745462153a4628756.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信