Javascript 从内环输出几个单元格
这是我的代码:Javascript 从内环输出几个单元格,javascript,arrays,loops,Javascript,Arrays,Loops,这是我的代码: start() { let columns = ['A'...'Z']; let fields = { id: [ 'Medlemsnummer', ], name: [ 'Namn', ], }; let out = {}; let self = this; columns.forEach(function(column) { for(let r
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);
},
如果您需要我更好地解释,请发表评论
亲切问候,
Joakim看着你的循环,我觉得你在自己的结构中迷失了一点
out[obj]=单元格
显然不正确obj
是一个对象,不能用作另一个对象中的键。这是我的笔记,希望我正确地解释了你的代码和你的问题。在初始化所有变量(如cell
,d_cell
等)后,我将从循环开始):
附录:在代码中,我坚持使用RegExp
测试字符串的解决方案。但是,如果只需要检查字符串是否以给定的子字符串开头,那么使用string.startsWith()
:
out=[medlemsnmmer:['A11'、'A23'、'A45'],name:['B11'、'B23']等等]
看起来不太对劲。你的意思可能是out=[{medlemsnmmer:['A11','A23','A45'],name:['B11','B23']}]
或类似的东西?你说得对,我很抱歉@商业自杀out
定义为顶部的对象。我怀疑它应该是out={medlemsnmmer:['A11','A23','A45'],name:['B11','B23']等等。}
它就像一个符咒!非常感谢你!你说得对,我有点迷路了。
out = [ medlemsnummer: ['A11','A23','A45'], name: ['B11','B23'] etc... ]
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);
}
}
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);
}