我有几个跨度:
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />
以及对它们的行动:
const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
if (typeof list[span.getAttribute('class')] === 'undefined') {
list[span.getAttribute('class')] = [];
}
list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});
console.log(list);
console.log(JSON.stringify(list));
但是JSON.stringify返回空数组。
如何计算给定跨度内出现的数据-id的数量-最简单的方法,然后再将其转换为string?我想把这些数据发送到API。
发布于 2019-08-24 01:13:33
下面是一个正在工作的代码:使用object而不是数组来拥有键。使用var而不是const来修改变量;
const spans = document.querySelectorAll('span');
var list = {};
spans.forEach(function(span) {
if (typeof list[span.getAttribute('class')] === 'undefined') {
list[span.getAttribute('class')] = [];
}
list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});
console.log(list);
console.log(JSON.stringify(list));
发布于 2019-08-24 01:23:36
如果您希望输出像这样的[{"first":["1"]},{"second":["4","2"]},{"third":["5"]}]
然后你就可以跟着这个阿帕罗克
const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
const className = span.getAttribute('class');
const valIndex = list.findIndex(val => val[className]);
const hasVal = valIndex !== -1;
if (className && hasVal) {
const preVal = list[valIndex][className];
list[valIndex][className] = preVal.concat(span.getAttribute('data-id'));
} else if (className && !hasVal){
list.push({[className]: [span.getAttribute('data-id')]});
}
});
console.log(list);
console.log(JSON.stringify(list));
这里是工作小提琴;
发布于 2019-08-24 01:13:08
我认为您希望list
成为一个对象,就像您试图通过类名访问list
的属性一样。
另外,与其使用forEach
修改外部对象,不如在从document.querySelectorAll()
调用返回的NodeList
上使用Array.prototype.reduce
:
const spans = document.querySelectorAll('span');
//With Array.prototype.reduce
const list = Array.prototype.reduce.call(spans, function(acc, span) {
const attr = span.getAttribute('class');
const dataId = span.getAttribute('data-id');
acc[attr] ? acc[attr].push(dataId) : (acc[attr] = [dataId]);
return acc;
}, {});
console.log(list);
console.log(JSON.stringify(list));
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />
https://stackoverflow.com/questions/57636535
复制