将数组的长度设置为 0 似乎不会清空数组
Setting an array's length to 0 seems not to empty the array
我正在使用全局javascript变量在Ajax请求后存储一些数据。它用于在jqueryui日期选择器上标记日期,并以array[date] = type_of_date
的形式存储
这是我用来计算数组的函数
function get_date_exceptii(data, cod_calendar) {
if(typeof(window.date_zile_ore_modificate) !== 'undefined' && typeof(window.date_zile_nelucratoare) !== 'undefined') {
window.date_zile_ore_modificate.length = 0;
window.date_zile_nelucratoare.length = 0;
}
else {
window.date_zile_ore_modificate = [];
window.date_zile_nelucratoare = [];
}
parametri = 'cod_calendar='+cod_calendar+'&data='+data;
$j.ajax({
url: "proiecte/ajax/colectare_date_exceptii.php?sid="+Math.random(),
type: 'POST',
async: false,
data: parametri
})
.done( function (msg) {
arr_msg = msg.split('[sep1]');
$j.each(arr_msg, function (index, val) {
arr_exceptie = val.split('[sep]');
if(arr_exceptie[1] == 'nelucratoare')
window.date_zile_nelucratoare[arr_exceptie[0]] = arr_exceptie[2];
else {
window.date_zile_ore_modificate[arr_exceptie[0]] = arr_exceptie[2];
}
});
});
console.log(window.date_zile_ore_modificate);
console.log(window.date_zile_nelucratoare);
}
当然,这两个日志用于调试。问题是即使执行了该部分代码,数组也永远不会被清除。我的语法是错误的还是我误解了这里的全局变量和/或数组?
arr_exceptie[0]
指定的索引可能是非数字的。
设置 length = 0
仅清除以数字命名的属性(根据 ES5 15.4.5.2(,因此不会清除具有非数字名称的属性。例如,如果设置 date_zile_ore_modificate['foo']
和 date_zile_ore_modificate[5]
,则设置 date_zile_ore_modificate.length=0
会清除 5
属性,但不会清除 foo
属性。
但是,将变量设置为全新的数组显然会清除所有属性,因为它完全消除了旧的数组对象。因此,只需使用
window.date_zile_ore_modificate = [];
window.date_zile_nelucratoare = [];
在所有情况下,并消除您的初始条件。
此外,如果您的属性名称完全是非数字的,则可能应该使用纯对象而不是数组(因为数组实际上仅适用于数字索引数据(:
window.date_zile_ore_modificate = {};
window.date_zile_nelucratoare = {};
相关文章:
- 当聚合管道中筛选的数组为空时,保留主文档
- 如何使select数组为空
- 如果数组为空,如何更改动态创建的数组JQplot
- 我们可以发送数据到控制器,直到我的数组变空
- 如何从数组中删除随机项目,然后将其从数组中删除,直到数组为空
- 从数组创建新元素,直到每秒数组为空
- JavaScript 过滤器方法返回过滤数组和空数组
- JavaScript 数组为空
- 交换 2 个项目在可观察数组 - 挖空
- 将 Json 数组挖空映射到可观察数组得到错误
- 拼接数组返回空的序列
- KnockoutJS:当返回的数组为空时显示消息
- Json 数组返回空值
- 如何防止向数组添加空值
- Knockout JS数组为空或可以't检索值
- 如何在不向输出数组获取空值的情况下拆分字符串
- 如果数组为空则转义以避免错误
- ajax成功函数后数组为空
- 数组为空Angular.js时不显示值
- 将数组传递给函数-函数内部的数组为空