我有一个数组var plans=[a, b, c, d ];
价格基于每月每年。如何在javascript中将数组拆分为两个数组?
Consider- a and b are monthly and c and d are yearly.
所以,我想拆基于月度,年度值的数组,并在值存储到独立阵列
var monthly_plans=[]; and var yearly_plans=[]
所以,我该怎么办呢?
我以前使用过js split()
函数,但在一个非常基础的层面上。
我有一个数组var plans=[a, b, c, d ];
价格基于每月每年。如何在javascript中将数组拆分为两个数组?
Consider- a and b are monthly and c and d are yearly.
所以,我想拆基于月度,年度值的数组,并在值存储到独立阵列
var monthly_plans=[]; and var yearly_plans=[]
所以,我该怎么办呢?
我以前使用过js split()
函数,但在一个非常基础的层面上。
我认为这将是一个更好的途径使用for
。
实施例:
for (var i=0;i<plans.length;i++)
{
if(plans[i] == 'monthly condition')
{
monthly_plans.push(plans[i]);
}
else
{
yearly_plans.push(plans[i]);
}
}
您可以在阵列上使用slice(start, end)
函数,例如,
monthly_plans = plans.slice(0,2);
yearly_plans = plans.slice(2,4);
更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
这工作,但不是通用解决方案当然,OP的实际阵列不仅仅是[a,b,c,d] –
根据您的文章,该解决方案将不涉及split()
。如果你事先计划其指定知道是每月和每年的是:
var plans = ['a', 'b', 'c', 'd', 'm', 'y', ....... 'n'],
count = plans.length, i = 0;
var monthly_designations = ['a', 'b', 'm'],
yearly_designations = ['c', 'd', 'y'];
for(; i < count; i++) {
if (monthly_designations.indexOf(plans[i]) !== -1) {
monthly_plans.push(plans[i]);
} else {
if (yearly_designations.indexOf(plans[i]) !== -1) {
yearly_plans.push(plans[i]);
}
}
}
然后,只需检查计划阵,与已知的名称到内容过滤到正确的子阵列monthly_plans
和yearly_plans
。
split()
不是Array
对象的String
对象的方法,。
从我从你的问题明白了,你需要Array.prototype.slice()
方法代替:
切片()方法返回一个数组 的一部分的浅拷贝到一个新的数组对象。
语法
arr.slice([begin[, end]])
总之,你可能想要做这样的事情:
var monthly_plans = plans.slice(0, 2);
var yearly_plans = plans.slice(2);
而且ES5方法:
var plans=[a, b, c, d];
var monthly_plans = plans.filter(plan => plan==='monthly condition');
var yearly_plans = plans.filter(plan => plan==='yearly condition');
感谢您的回复。 循环中的每月条件是什么?我的意思是它在做什么? –
您必须将其替换为您想要考虑的值为每月计划的条件。 –
因此,在我的情况下,irs'“cpinterval”:“每月”' 所以,它会像计划[我]。cpinterval ==“每月” –