任何人都可以帮助我理解为什么以下这个不起作用?如果元素中包含超过5个div,我希望得到真实。
var hasMorethanFiveDiv = function(domElement, divCounter) {
// div counter variable(divcounter)
divCounter = divCounter || 0;
// if the current node has div
if(domElement.tagName === "DIV"){
divCounter++;
}
//iterate over children nodes
for(var i=0; i<domElement.children.length; i++){
// invoke hasMorethanFiveDiv on a child element.
hasMorethanFiveDiv(domElement.children[i], divCounter);
}
//return true if divCounter is bigger than 5
return divCounter >= 5;
};
答案 0 :(得分:1)
这是这一行:
hasMorethanFiveDiv(domElement.children[i], divCounter);
divCounter不是通过引用传递的,而是通过值传递的。这意味着如果在函数中修改了divCounter,则不会返回更新。
// Variable are sent by value
var value = 1;
var addValue = function(arg) {
arg++; // arg value is now 2, but only for the scope of this function
}
addValue(value);
alert(value); // alert 1 NOT 2...
// Objects are sent by reference
var obj = {
value: 1
}
var addValue2 = function(arg) {
arg.value++;
}
addValue2(obj);
alert(obj.value); // alert 2
一个工作示例:
var hasMorethanFiveDiv = function(domElement) {
//return true if divCounter is bigger than 5
var objCounter = {counter: 0};
divCounter(domElement, objCounter);
return objCounter.counter >= 5;
};
var divCounter = function(domElement, objCounter) {
// div counter variable(divcounter)
// if the current node has div
if(domElement.tagName === "DIV"){
objCounter.counter++;
}
//iterate over children nodes
for(var i=0; i<domElement.children.length; i++){
// invoke hasMorethanFiveDiv on a child element.
divCounter(domElement.children[i], objCounter);
}
}
alert(hasMorethanFiveDiv(document.getElementById("main1")));
alert(hasMorethanFiveDiv(document.getElementById("main2")))
<div id="main1">
<div></div>
<div></div>
<div><div></div><div></div></div>
<div></div>
</div>
<div id="main2">
<div></div>
<div></div>
</div>