使用javascript创建堆叠数组
我有一个原始的二维数组,表示每年100%的版本预算,如下所示:使用javascript创建堆叠数组,javascript,arrays,multidimensional-array,slice,Javascript,Arrays,Multidimensional Array,Slice,我有一个原始的二维数组,表示每年100%的版本预算,如下所示: budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]] 现在我需要为项目创建预算的子数组。例如: project1 = [['2001-01-01', 10], ['2001-01-02', 11]] 这意味着,它将持续2天,并使用可用预算的10% 我通过以下函数创建项目数组: project1 = [[]]; project1
budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]]
现在我需要为项目创建预算的子数组。例如:
project1 = [['2001-01-01', 10], ['2001-01-02', 11]]
这意味着,它将持续2天,并使用可用预算的10%
我通过以下函数创建项目数组:
project1 = [[]];
project1 = new_project(budget, 0, 1, 0.1);
function new_project(origin, start, end, factor) {
var result = [[]];
result = origin.slice(parseInt(start), parseInt(end)).map(function (item) {
return [item[0], parseInt(item[1]) * factor]
});
return result;
}
问题
我现在如何通过创建项目的值来减少预算数组?
我需要通过调用new_project动态修改预算,以便获得:
budget = [['2001-01-01', 90], ['2001-01-02', 99],..., ['2001-12-31', 140]]
设置的中间部分
我得到了答案。看
解决方案
功能新建项目(起点、起点、终点、系数){
var结果=[
[]
];
结果=origin.map(函数(项){
返回[项目[0],(项目[1]*系数)]
});
对于(变量i=0;i
您可以使用内置数组forEach()
方法循环预算子集(即project1)并更改原始预算的值。我已经创建了一个名为DecreaseBudent()
的函数,它将为您执行以下操作:
function decreaseBudget(original, subset) {
// Loop over the subset's items.
subset.forEach(function(item, index){
// Get the original amount out of the original item.
// As we are looping over subset it will always have less items then the original
// so no need to check if the index is valid.
var originalItemAmount = original[index][1];
// Decrease the amount and set it back in it's original place
original[index][1] = (originalItemAmount - item[1]);
});
};
使用budget
和project1
数组作为参数调用它,以更改budget
数组的值。看看更新的小提琴:
如果您希望
DecreaseBrudge()
不会更改原始数组,而是返回一个副本,则可以使用array.slice()方法创建原始数组的浅层副本,对副本进行更改并返回它。为什么要在“start”、“end”和“item[1]”参数上调用parseInt?你没必要这么做,你是对的。有时,起始日期由第/12年确定。一年是365年。12年我得到了30,41。。这就是为什么要筛选出新的_项目结果中存在或不存在的一些预算数组成员?我想通过项目数组的第二个元素来减少预算数组的第二个元素。因此它将是['2001-01-02',99]?
function decreaseBudget(original, subset) {
// Loop over the subset's items.
subset.forEach(function(item, index){
// Get the original amount out of the original item.
// As we are looping over subset it will always have less items then the original
// so no need to check if the index is valid.
var originalItemAmount = original[index][1];
// Decrease the amount and set it back in it's original place
original[index][1] = (originalItemAmount - item[1]);
});
};