我有现有的数组:
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
函数返回一个字符串。我需要一种方法将对honda
或toyota
数组的引用传递给另一个函数,让我们说randomizeSelection(chooseMake)
从任一选定数组中返回一个随机值。
我已经有了随机函数功能。我需要一种方法来传递它,这个数组匹配用户的选择...而不是字符串。
答案 0 :(得分:2)
这里的解决方案是将数组放入对象中。这样,数组名称就可以作为字符串的对象属性的引用来访问。
现在,对于你的随机功能,你真的不需要将它与数组的获取分开,但根据你的要求,这里有两个功能一起工作以获得一辆随机的车:
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)];
}
});
&#13;
<select id="vehicles">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
</select>
&#13;