使用数组从条件循环的结果中获取值
Posted
技术标签:
【中文标题】使用数组从条件循环的结果中获取值【英文标题】:get value from result of conditioned loop with array 【发布时间】:2021-09-25 17:08:00 【问题描述】:如何获取不是数组[0,2,3,4]的值的循环的值,我把这个数组放在“补栏”变量中。
假设我有循环 0 - 11 (0,1,2,3,4,5,6,7,8,9,10,11) 的结果值,我想得到值 (1 ,5,6,7,8 ,9,10,11)
const d = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dataWaktu = [];
var dataIzin = [];
var dataCuti = [];
var dataSakit = [];
var Bulan = []; //[0,2,3,4]
var dataLeave = [];
for (var i = 0; i < monthNames.length; i++)
var existData = true;
$.each(data, function(index, val)
if(val.Bulan == monthNames[i] )
// console.log(i);
Bulan.push(val.Bulan);
existData = true; return;
else
// console.log(i);
existData = false;
);
if(existData)
$.each(data, function(index, val)
dataLeave.push( Bulan: val.Bulan, Cuti: val.Cuti, Izin: val.Izin, Sakit: val.Sakit );
);
else
//output : 1 5 6 7 8 9 10 11
// dataLeave.push( Bulan:monthNames[i], Cuti: 0, Izin: 0, Sakit:0 );
console.log(i); //0 1 2 3 5 6 7 8 9 10 11
;
【问题讨论】:
【参考方案1】:试试下面的代码:
let numbers = [0,1,2,3,4,5,6,7,8,9,10,11];
let numbersToRemove = [0,2,3,4];
let newNumbers = numbers.filter(number => !numbersToRemove.includes(number) );
console.log(newNumbers) // 1,5,6,7,8,9,10,11
【讨论】:
【参考方案2】:你可以试试这个
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var Bulan = [0,2,3,4];
// create new array of monthNumber that are needed
var monthNumbers = []
for (let i = 0; i < monthNames.length; i++)
if (Bulan.includes(i) === false)
monthNumbers.push(i)
console.log(monthNumbers) // it will show [1,5,6,7,8,9,10,11]
【讨论】:
如果我将 0.2,3,4 放入一个数组中,该怎么做?我已经循环这个数组并创建了一个条件,结果是 1,2,3(2), 5(4)等 我已经更新了答案,这是你的意思吗? @creatorlife 嘿?您能否通过使用检查或投票来判断它是否已经正确......?所以社区会明白,如果以后遇到像你一样的问题@creatorlife以上是关于使用数组从条件循环的结果中获取值的主要内容,如果未能解决你的问题,请参考以下文章
如何从带有条件的 React Native 中的 API 数组结果中获取记录?
jquery循环获取值想依次添加到数组里,再怎么从数组中取出值