当我第一次从第二个选择菜单中选择两个选项时,数组中将填充这两个选项。我想要的是第二个选定的选项替换第一个,所以即使我从第二个选择菜单中选择两个选项开始,数组的长度也将保持为 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()
首先要增加值(value)。您可以检查数组中是否存在元素
使用 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);
}
关于javascript - 切片数组中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056021/