gpt4 book ai didi

javascript - Jquery 将值添加到数组(如果不存在)

转载 作者:行者123 更新时间:2023-12-01 03:36:39 25 4
gpt4 key购买 nike

我有以下函数,如果数组不存在,它应该将值添加到数组中。

    var category_json = new Array();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>Reports/appointment_distribution_by_group/",
dataType: 'JSON',
data: {county: county, sub_county: sub_county, facility: facility, date_from: date_from, date_to: date_to},
success: function (data) {
// Populate series
for (i = 0; i < data.length; i++) {
/* Values returned from variable data as data[i].group_name = > Adolescents,Adolescents,All,All,ART Clients,ART Clients,ART Clients,ART Clients,Lactating woman,New Clients,New Clients,Paeds on ART,Paeds on ART,PMTCT,PMTCT */
if(jQuery.inArray(data[i].group_name,category_json)!== -1) {
//element exists in array
console.log(" Found ..." + data[i].group_name);
} else {
//element not found in array
category_json.push([data[i].group_name]);
console.log("Not Found ..."+data[i].group_name);
console.log(category_json);
}

}
var type = jQuery.type(category_json);
alert(category_json);
alert(type);
// draw chart

}, error: function (errorThrown) {

}});

我想将返回值添加到类别 json 数组中,但仅限唯一值。但是,检查数组中的值根本不会返回 true。我应该使用哪个条件来检查数组中是否存在该值?

最佳答案

将元素推送到另一个数组中的数组

你的代码category_json.push([data[i].group_name]);

应该像这样 category_json.push(data[i].group_name);

示例:

var arr = [1, 2];

arr.push([3]);

console.log(arr); // [1, 2, [3]]

之后你像这样检查arr.indexOf(3)并且总是返回-1

关于javascript - Jquery 将值添加到数组(如果不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com