这是我的代码:
start() {
let columns = ['A'...'Z'];
let fields = {
id: [
'Medlemsnummer',
],
name: [
'Namn',
],
};
let out = {};
let self = this;
columns.forEach(function(column) {
for(let row = 1; row < 101; row++) {
let cell = column + row;
let d_cell = self.worksheet[cell];
let val_cell = (d_cell ? d_cell.v : ' ');
let cell_string = val_cell.toString().toLowerCase();
let cellString_stripped = cell_string.replace(/(?:\r\n|\r|\n)/g, '');
for (var key in fields) {
// skip loop if the property is from prototype
if (!fields.hasOwnProperty(key)) continue;
var obj = fields[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if(!obj.hasOwnProperty(prop)) continue;
obj.forEach(function(term) {
if(cellString_stripped.match(new RegExp(term.toLowerCase() + ".*"))){
//out.push(obj + ': ' + cell);
//out[obj] = {cell};
out[obj] = cell;
}
});
//out[obj]
}
}
}
});
console.log(out);
},
我的问题是我想在out [obj] = //匹配单元格数组中找到几个匹配的单元格。
我怎样才能在javascript中执行此操作?
所以我的外表应该是这样的:
out = [ medlemsnummer: ['A11','A23','A45'], name: ['B11','B23'] etc... ]
如果您需要我更好地解释,请发表评论。
亲切的问候,
乔金姆
答案 0 :(得分:2)
看着你的循环,我觉得你在自己的结构中有点迷失。 out[obj] = cell
肯定不对; obj
是一个对象,它不能用作另一个对象的键。这是我对一些笔记的看法,希望我能正确地解释你的代码和你的问题。在初始化了所有变量(例如cell
,d_cell
等)后,我将从循环开始:
for (let key in fields) {
if (!fields.hasOwnProperty(key)) continue;
let terms = fields[key];
// fields[key] yields us an array, e.g.:
// fields['id'] = [ 'Medlemnummer' ]
// so we can iterate over it directly with for..of.
// Note also: variable names like "obj" make reading your code
// difficult; use meaningful names, e.g. "terms".
for (let term of terms) {
let regex = new RegExp(term.toLowerCase() + ".*");
// Note: RegEx.test() is more efficient than String.match()
// if all you need is a yes/no answer.
if (!regex.test(cellString_stripped)) continue;
// Here's the part you actually needed help with:
if (!out[term]) {
out[term] = [];
}
out[term].push(cell);
}
}
附录:在代码中我坚持使用RegExp
来测试字符串的解决方案。但是,如果您需要检查的是字符串是否以给定的子字符串开头,那么使用String.startsWith()
的时间要短得多且效率更高:
for (let term of terms) {
if (!cellString_stripped.startsWith(term.toLowerCase())) continue;
// Here's the part you actually needed help with:
if (!out[term]) {
out[term] = [];
}
out[term].push(cell);
}