gpt4 book ai didi

javascript - 从 onChange 处理程序引用现有数组

转载 作者:行者123 更新时间:2023-11-30 15:36:34 25 4
gpt4 key购买 nike

我有现有的数组:

var honda = [ 'civic', 'accord' ];
var toyota = [ 'corolla', 'camry' ];

用户可以选择车辆品牌:

<select id="vehicles">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
</select>

我在更改时添加一个事件监听器以找到他们的选择:

var vehicleSelect = document.getElementById('vehicles');
vehicleSelect.addEventListener('change', chooseMake, false);

var chooseMake = function() {
var selected = vehicleSelect.value;
return selected;
};

我的问题:chooseMake 函数返回一个字符串。我需要一种方法将对 hondatoyota 数组的引用传递给另一个函数,假设返回随机值的 randomizeSelection(chooseMake)来自任一选定数组的值。

我已经有了随机发生器功能。我需要一种方法来传递给它,匹配用户选择的数组...而不是字符串。

最佳答案

此处的解决方案是将数组放入一个对象中。这样,数组名称就可以作为对对象属性字符串的引用来访问。

现在,对于您的随机函数,您实际上不需要将它与数组的获取分开,但根据您的要求,这两个函数一起工作以获取随机汽车:

window.addEventListener("DOMContentLoaded", function(){

// Object properties are accessible as strings when bracket notation ([])
// is used. By placing the arrays into an object as properties, you give
// yourself the option to reference those properties as strings later.
var makes = {
honda : [ 'civic', 'accord', 'odyssey', 'crv', 'ridgeline' ],
toyota : [ 'corolla', 'camry', 'sienna', 'avalon']
};

// Get reference to DOM <select> and set up an event handler for it
var vehicleSelect = document.getElementById("vehicles");

// Rather than set the event handler to a named function (which we couldn't
// pass custom arguments to since it's an automatically called function),
// we'll have the handler be an anonymous wrapper function.
vehicleSelect.addEventListener('change', function(){
// Within the wrapper function, we can do whatever we like, including
// calling other functions with any values we want.

// Call the function that gets the correct array out of the object
// based on the string value of the select at this moment.
var result = chooseMake();

// Take the array and pass it to the randomizing function and log the returned
// random value:
console.log(randomizeSelection(result));
});

// When the select value changes get the array corresponding to the string
// value of the select
function chooseMake() {
return makes[vehicleSelect.value];
}

// Take in the selected array and return a specific car from that array
// based on a random selecton:
function randomizeSelection(make){
return make[Math.floor(Math.random() * make.length)];
}
});
<select id="vehicles">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
</select>

关于javascript - 从 onChange 处理程序引用现有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com