【发布时间】:2015-01-07 13:20:20
【问题描述】:
我正在尝试使用来自 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"]
【问题讨论】:
-
this是保留关键字,您不应将变量附加到它 -
inArray如果未找到 api.jquery.com/jquery.inarray,则返回-1。所以它仍然是正确的。你必须检查>-1。 -
@devqon 我知道,我只是在我的示例中使用了它。在我的工作代码中,我使用其他非保留名称。
-
呵呵,根特的学生?
-
请再次查看jsfiddle.net/dr1bxwqf/2,我已经更新了
标签: javascript jquery arrays ajax