This code is made to generate a list of unique elements of the array made of the other two arrays. The fact that we need two lists to convert in two different array is part of the task. This code handles with the task, but there's a lot of global variables. As far as I know, it is not good practice. Tell me, please, how can I improve it?
<body id="body">
<div>
<ul id="ul1">
<li>Любовь</li>
<li>Надежда</li>
<li>Вера</li>
</ul>
</div>
<div>
<ul id="ul2">
<li>София</li>
<li>Надежда</li>
<li>Вера</li>
</ul>
</div>
<button id="makeNewArray">Создать новый массив</button>
<script type="text/javascript">
function init() {
var btn = document.getElementById('makeNewArray'),
arrLi1 = ul1.getElementsByTagName('li'),
arrLi2 = ul2.getElementsByTagName('li'),
arr1 = [],
arr2 = [],
result = [];
for (var i = 0; i < arrLi1.length; i++) {
arr1.push(arrLi1[i].innerHTML);
}
for (var j = 0; j < arrLi2.length; j++) {
arr2.push(arrLi2[j].innerHTML);
}
commonArr = arr1.concat(arr2);
nextInput:
for (var k = 0; k < commonArr.length; k++) {
var str = commonArr[k];
for (var l = 0; l < result.length; l++) {
if (result[l] == str) continue nextInput;
}
result.push(str);
}
btn.onclick = function() {
var div = document.createElement('div');
div.innerHTML = result;
body.appendChild(div);
};
};
window.onload = init;
</script>
</body>
init
, you can declarecommonArray
andstr
in that function too. Unless they are used in some other script too. A common way is to enclose all the script within a single IIFE, that way you wouldn't have to use globals at all. \$\endgroup\$