gpt4 book ai didi

javascript - 如果不在数组中 -> array.push

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

我正在尝试使用来自 JSON 提要的独特元素在 javascript 中创建一个数组。也许我在 php 中想了很多,但有一个简单的脚本,如下所示。

$this = array();
foreach($array as $key => $value) {
if (!in_array($value,$this)) {
array_push($this,$value);
}
}

在 JS 中它不会:

var this = new Array();
$.each(data, function(i,field) {
var value = field['needed'];
if (!$.inArray(value, this)) {
this.push(value);
}
}

它只是将每个 field['needed'] 添加到 this

完整的代码让你知道我是如何得到我的 JSON

$(function() {
$("#wtf").empty();
$.getJSON("http://localhost/ahsmedia/openingsuren/api.php?first=" + cal.currentDate.format('d-m-Y'),
function(data) {
var camp = new Array();
$.each(data, function(i,field) {
var dt = field['datum'];
var ca = field['campus'];
var ca = ca.toLowerCase();
if ($.inArray(ca, camp)) {
camp.push(ca);
}

$("#wtf").append(field['campus'] + ' ' + cal.currentDate.format('d-m-Y') + ': ' + " " + field['open'] + "-" + field['close'] + " " + field['type'] + "<br />");
});
console.log(camp);
});
});

JSON 看起来像:

[
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kantienberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kattenberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Mariakerke",
"open": "08:30:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "09:30:00",
"close": "11:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "12:00:00",
"close": "17:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "08:15:00",
"close": "12:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "13:30:00",
"close": "17:30:00"
}
]

在检查字段是否在数组中之前,我可能忘记了一个重要的步骤,但我对此很陌生,所以我没有找到它。

要清楚,我需要一个包含每个独特校园的数组,例如

['Kantienberg','Kattenberg','Mariakerke','Sint-Amandsberg','Sint-Annaplein']

但是我明白了

["kantienberg", "kattenberg", "mariakerke", "sint-amandsberg", "sint-amandsberg", "sint-annaplein", "sint-annaplein"]

最佳答案

$.inArray() 如果数组中不存在该值,则返回 -1。当用作 bool 值时,-1 等同于 true。您需要更改条件以显式检查 -1:

if ($.inArray(ca, camp) == -1) {
camp.push(ca);
}

Example fiddle

关于javascript - 如果不在数组中 -> array.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820461/

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