当尝试返回在对象中找到的包含:host的子代数量时,该函数始终返回undefined
。
const plugin = stylelint.createPlugin(ruleName, isEnabled => {
let childrenFound = 0;
childrenFound = lookForChildren(rule.nodes, childrenFound);
console.log(childrenFound); // Wrong Value: Always undefined
}
let lookForChildren = function(nodes, childFound) {
if(childFound > 1) {
console.log(childFound);
return childFound;
}
nodes.forEach(node => {
if (node.selector != undefined) {
const selector = node.selector.replace(":host-context", "");
if (selector.includes(":host")) {
childFound++;
return lookForChildren(node.nodes, childFound);
} else {
return lookForChildren(node.nodes, childFound);
}
}
});
// This returns the wrong value so i deleted it
return childFound;
};
但是它应该返回childFound变量,该变量仅在大于1时才返回。
此功能检查scss文档是否包含一个选择器,该选择器具有多个:host
选择器,因为浏览器对它的编译与预期不同。
childFound
大于1时:
预期:return childFound // Childfound is 2 or higher
实际:childrenFound
始终未定义。
答案 0 :(得分:1)
使用for...to
解决了我的问题。感谢@HarunYilmaz指出这一点,并感谢大家为我提供帮助。
答案 1 :(得分:0)
您应该在函数内部返回值,而不是在该函数之外或之下,只需更改return语句在最后一个花括号内的位置即可。检查以下代码:
const plugin = stylelint.createPlugin(ruleName, isEnabled => {
let childrenFound = 0;
childrenFound = lookForChildren(rule.nodes, childrenFound);
console.log(childrenFound); // Wrong Value: Always undefined
}
let lookForChildren = function(nodes, childFound) {
if(childFound > 1) {
console.log(childFound);
return childFound;
}
nodes.forEach(node => {
if (node.selector != undefined) {
const selector = node.selector.replace(":host-context", "");
if (selector.includes(":host")) {
childFound++;
return lookForChildren(node.nodes, childFound);
} else {
return lookForChildren(node.nodes, childFound);
}
}
});
return childFound;
};
// This returns the wrong value so i deleted it