javascript - 切片数组中的节点

标签 javascript html arrays list slice

当我第一次从第二个选择菜单中选择两个选项时,数组中将填充这两个选项。我想要的是第二个选定的选项替换第一个,所以即使我从第二个选择菜单中选择两个选项开始,数组的长度也将保持为 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/

相关文章:

javascript - ReactJS本地主机Ajax调用: No 'Access-Control-Allow-Origin' header

javascript - Tensorflow.js 中的图像大小调整方法(resizeBilinear 和 resizeNearestNeighbor)不会返回正确的结果

javascript - 在一个div中制作超过4个顶点

android - 如何在 android webview 中处理 mailto[HTML]

javascript - 使用 css 或 jquery 将一张图片淡入另一张图片

ruby-on-rails - Rails,将整数转换为数组偏移量

c - 用字符串的一部分填充二维数组

javascript - 如何在具有html的变量中使用变量

javascript - 如何在 Apps 脚本中设置 "Disable options to download, print, and copy for commenters and viewers"

php - 使用数据库数据构造 php 数组