使用 push() 方法和 indexOf() 方法从 AngularJS1 中的数组中删除

我能够提取 EPOCH 日期并将它们成功转换为字符串,但是我之前编写的代码没有检查或删除重复项。任何人都知道我可以添加什么来做到这一点?在这种情况下,时间戳是我从实时数据中提取的 EPOCH 日期!角度JS1



慕码人2483693
浏览 131回答 3
3回答

www说

var dateMap = {};for (i = 0; i < dbData.length; i++) {&nbsp; let tmp_date_str = "";&nbsp; let tmp_date = new Date(dbData[i].TIMESTAMP);&nbsp; tmp_date_str += tmp_date.getFullYear();&nbsp; tmp_date_str += "-";&nbsp; if ((tmp_date.getMonth()+1) < 10) {&nbsp; &nbsp; &nbsp; tmp_date_str += "0";&nbsp; }&nbsp; tmp_date_str += (tmp_date.getMonth()+1);&nbsp; tmp_date_str += "-";&nbsp; if (tmp_date.getDate() < 10) {&nbsp; &nbsp; &nbsp; tmp_date_str += "0";&nbsp; }&nbsp; tmp_date_str += tmp_date.getDate();&nbsp; &nbsp; // make it a map, and if value for this string already exists, do nothing&nbsp; if (!dateMap[tmp_date_str]) {&nbsp; &nbsp; dateMap[tmp_date_str] = true;&nbsp; }}如果您需要将日期作为数组获取,那就去做&nbsp; var dates = Object.keys(dateMap)

largeQ

您可以使用set来消除重复:const mySet= new Set(["one", "two", "three", "one"]);mySet.has("one") // true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;mySet.size === 3); // trueSet 构造函数可以采用一组用于初始化集合的项目。

BIG阳

要检查并删除重复项,您可以使用angular.equals:var newArray = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; angular.forEach($scope.dates, function(value, key) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var exists = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; angular.forEach(newArray, function(val2, key) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(angular.equals(value.date, val2.date)){ exists = true };&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(exists == false && value.dates != "") { newArray.push(value); }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $scope.dates = newArray;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript