javascript - GREP 未检测到数组中添加的元素
问题描述
我从后端加载了一个包含 100 个元素的数组。
console.log(array)
显示 100 个元素。
然后我通过 ajax 获得 1 个新元素并将其添加到数组中array.push(new_element);
console.log(array)
显示 101 个元素。
如果我console.log(array[array.length-1])
得到我添加的元素。
到目前为止一切正常,数据正确。这是从添加的元素中捕获的。
然后我想在列表中显示选定元素的子集。
sub_array = jQuery.grep(array, function(n) { return ( n.selected === 'True' });
添加的 101 元素被“选中”,确认,但我没有进入 sub_array。
我检查了所有逻辑,没关系。不明白为什么我没有得到 101 元素。
似乎 grep 命令从原始版本而不是更新版本获取数组数据。
就像它进入更深层次的记忆或类似的东西。那可能吗?
一些代码
// Part 1 - The original data comes from Django backend
$(document).ready(function(){
window.array = {{ course_list|safe }};
};
// Part 2 - Adding extra value
$.ajax({
url:'/myurl',
contentType : "application/json",
dataType: 'json',
success:function(data){
console.log(array);
// Here I get the correct number of 100 elements
new_course = JSON.parse(data.extra_course);
array.push(new_course);
console.log(array);
// Here I get the correct number of 101 elements
},
error:function(data){
},
});
// Part 3 -
function create_agenda() {
console.log(array[array.length-1]);
// Here I get the added element correctly
sub_array = jQuery.grep(array, function(n) { return ( n.selected === 'True') });
// Here I don't get the element. Even filtering by other fields
};
sub_array 项目示例
欢迎任何线索!谢谢。
解决方案
在ajax
repsonse 中,data.extra_course
它是一个数组而不是一个对象。
您将必须获取第一个元素extra_course
并将其推送到array
如下所示:
$.ajax({
url: '/myurl',
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(array);
// Here I get the correct number of 100 elements
new_course = JSON.parse(data.extra_course); // THIS RETURNS AN ARRAY
array.push(new_course[0]); // < ------------- USE THE FIRST OBJECT HERE
console.log(array);
// Here I get the correct number of 101 elements
},
error: function (data) {
},
});
推荐阅读
- python - Python HTML Hex代码到字符,反之亦然
- sockets - 关于 select() 的问题
- api - GeneXus 是否具有调用外部程序 API 的功能?
- report - cognos 10.2.2 - 报表工作室
- c++ - 使用向量扩展的快速对称二进制矩阵乘法
- python-3.x - Python 3.7 - 下载图像 - Urllib.request.urlretrieve 错误
- inner-join - 基于情感分析将自定义(加权)字典应用于文本
- php - 切片发票客户区扩展:添加重新排序按钮
- excel - Excel 2011 for Mac - 如果事先选择了文件->打印,则输出 PDF 失败
- azure-cosmosdb - Cosmosdb 跨分区查询问题