当我第一次从第二个选择菜单中选择两个选项时,将使用这两个选项填充数组。我想要的是第二个选择的选项替换第一个,所以即使我从第二个选择菜单中选择两个选项开始,数组的长度将保持为1,在这些选择之间动态变化。我希望你明白。谢谢你的帮助。我知道我可以让它成为一个功能,这个问题不会存在,但是对于我的使用,我不能这样做。
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = []
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
array.splice(0, 1, one);
console.log(array);
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(1, 1, two);
console.log(array);
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
使用Array.prototype.unshift()
在第一时间增加价值。您可以使用includes()
检查数组中是否存在元素。
而不是创建两个函数,您可以创建相同的函数并传递不同的参数。
var array = [];
function myFunct(val){
if(!array.includes(val)) array.unshift(val);
console.log(array);
}
<button onclick = 'myFunct("One")'>ONE</button>
<button onclick = 'myFunct("Two")'>TWO</button>
如果要使用第一个值替换新值,请使用此代码
function myFunct(val) {
array.unshift(val);
array = [... new Set(array)];
console.log(array);
}
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = [];
let sel1 = false;
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
if(array.length === 1 && !sel1) array.unshift(one);
else array.splice(0,1,one);
console.log(array);
sel1 = true;
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(sel1, 1, two);
console.log(array);
}
试试这个:
var array = [];
function myFunct() {
if(array.indexOf('One') === -1 ) { array.unshift('One') ; }
console.log(array);
}
function myFunct2() {
if(array.indexOf('Two') === -1 ) { array.push('Two') ; }
console.log(array);
}
<button onclick = 'myFunct()'>ONE</button>
<button onclick = 'myFunct2()'>TWO</button>