我正在创建两个给定日期之间的天数组,键的格式应为DD / MM / YYYY,值应为数字(每个日期设置的价格)
它似乎起作用了,因为该数组包含我通过日期选择器提供的值,但我无法遍历该数组,可能是因为即使它包含元素,它的长度也会返回0
这是控制台日志语句的屏幕截图
这是创建数组的代码
var arrayOfDatesBetween = new Array();
// daysBetween = integer representing the count of days between the chosen dates
for (let i = 0; i < daysBetween; i++) {
// just add one day on each iteration but keep count of the first
let q = i === 0 ? i : 1;
let _date = _dateIn.setDate(_dateIn.getDate()+q);
// lcsgDate() formats the date as I need it: DD/MM/YYYY
let __date = lcsgDate(_date);
// getDatePrice() gets the price for the given date by searching into another Array of date:price
arrayOfDatesBetween[__date] = getDatePrice(__date);
}
// result
console.log(arrayOfDatesBetween);
答案 0 :(得分:0)
我确认将arrayOfDatesBetween
从Array更改为Object可以解决此问题,现在我可以根据需要使用非整数作为键,谢谢您的评论并指出正确的方向
答案 1 :(得分:0)
let arr = [1,2,3]
arr['someCustomDate'] = 'someCustomData'
console.log(arr) // [1,2,3]
console.log(arr['someCustomDate'])
您的代码本质上与上面的代码相同,您是在定义数组的属性,而不是将其压入数组。
要处理您的情况,您有两种选择:
1::为数组中的每个元素创建一个对象,并将其按如下所示推入数组:
var arrayOfDatesBetween = new Array();
// daysBetween = integer representing the count of days between the chosen dates
for (let i = 0; i < daysBetween; i++) {
// just add one day on each iteration but keep count of the first
let q = i === 0 ? i : 1;
let _date = _dateIn.setDate(_dateIn.getDate()+q);
// lcsgDate() formats the date as I need it: DD/MM/YYYY
let __date = lcsgDate(_date);
// getDatePrice() gets the price for the given date by searching into another Array of date:price
//HERE <=======
let newObjectElement = { date: __date, price: getDatePrice(__date)};
//arrayOfDatesBetween[__date] = getDatePrice(__date);
arrayOfDatesBetween.push(newObjectElement);
}
// result
console.log(arrayOfDatesBetween);
2 :保留您的代码,但使用Object.keys
遍历__date
。
强烈建议选择选项1,因为这是使用Array
而不是将element作为键的唯一原因