Javascript 我可以在空数组中搜索吗?
我的问题是关于这一部分:Javascript 我可以在空数组中搜索吗?,javascript,arrays,Javascript,Arrays,我的问题是关于这一部分: <script> function multiple(arr) { var counter = []; //counter is the occurrence of a specific element in an array var unique = []; //the actual element in the array var found; //the index showing if the
<script>
function multiple(arr) {
var counter = []; //counter is the occurrence of a specific element in an array
var unique = []; //the actual element in the array
var found; //the index showing if the element is already in the counter
for (var i = 0; i < arr.length; i++) {
found = 0;
for (var j = 0; j < unique.length; j++) {
if (unique[j] == arr[i]) { //
found = 1;
counter[j] = counter[j] + 1;
}
}
if (found == 0) { //if it's the element's first apperance in the array
unique.push(arr[i]);
counter.push(1);
}
}
var result = [];
for (var i = 0; i < unique.length; i++) {
result.push([unique[i], counter[i]]);
}
return result;
}
console.log(multiple([5,1,5,6,3,4,6]));
</script>
但当i=0和j=0时,数组unique为空。在搜索过程中它不会被定义吗?但是,此功能可以工作。我想知道为什么 for循环在进入循环体之前检查其状态。当unique为空时,unique.length为0,对问题0A for循环的回答在进入循环体之前检查其条件。当unique为空时,unique.length为0,对于var j=0,如果unique为空,则问题0的答案为空;j<唯一长度;j++{不运行循环的内容。如果变量j=0的unique为空;j
for (var j = 0; j < unique.length; j++) {
if (unique[j] == arr[i]) {
for (var j = 0; j < unique.length; j++) {
...
}
var j = 0;
while( j < unique.length ) {
...
j++;
}