我想随机地从数组创建一个数组,但我开始使用javascript。这是我的问题。
<p id "demo1"></p>
<p id "demo2"></p>
<p id "demo3"></p>
CREATE TABLE #FilesList(ID INT IDENTITY(1,1), FileName VARCHAR(1000),Depth INT,isFile INT)
INSERT INTO #FilesList
EXEC xp_dirtree @FilePath, 1, 1
我想我必须将双引号 - “house” - 字符串转换为object - house - 转换为var并在输入系统之前?
答案 0 :(得分:1)
我不是100%肯定你在这里问的是什么,但我相信你想要的行为可以用2d数组完成 -
const t = [["red","blue","orange","black"], ["silver", "gold", "cooper","plastic"], ["marble","oak","yep","pine"], ["computer","mobile","mac","tablet"]]
const [rand1, rand2] = [Math.floor(Math.random() * t.length), Math.floor(Math.random() * t[0].length)]
console.log(t[rand1][rand2])
答案 1 :(得分:0)
您可以使用switch
函数来获取对象引用,但它可能会导致毛病问题,因此最好使用其他选项,例如//array
var t = ["house","pen","table","electronic"];
var house = ["red","blue","orange","black"];
var pen = ["silver", "gold", "cooper","plastic"];
var table = ["marble","oak","yep","pine"];
var electronic = ["computer","mobile","mac","tablet"];
var w = Math.floor(Math.random() * 3); // random type index (0 to 3)
var x = t[w]; // name of the random type
var y = Math.floor(Math.random() * 3); // random option (0 to 3)
switch (w) { // use the appropriate object based on type index
case 0: z=house[y]; break;
case 1: z=pen[y]; break;
case 2: z=table[y]; break;
case 3: z=electronic[y]; break;
}
console.log(w, z);
var z = z + ' ' + x // appending "house" to color
console.log(z);
document.getElementById("demo1").innerHTML=z;
语句:
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
&#13;
<audio id="my_audio" >
<source src="bark.mp3" type="audio/mpeg">
</audio>
<audio id="my_audio2">
<source src="roar.mp3" type="audio/mpeg">
</audio>
<audio id="my_audio3">
<source src="hoot.mp3" type="audio/mpeg">
</audio>
<script type="text/javascript">
$(document).ready(function() {
$("#my_audio").get(0).play();
$("#my_audio").bind("ended", function(){
setTimeout(function() { $("#my_audio2").get(0).play(); },2000);
$("#my_audio2").bind("ended", function(){
setTimeout(function() { $("#my_audio3").get(0).play(); },2000);
});
});
});
</script>
&#13;
答案 2 :(得分:0)
如果这是您正在寻找的内容,我不太清楚,但一种解决方案可能是构建您的数据,以便更容易获得:
const items = {
house: ["red","blue","orange","black"],
pen: ["silver", "gold", "cooper","plastic"],
table: ["marble","oak","yep","pine"],
eletro: ["computer","mobile","mac","tablet"]
}
const randomChoice = list => list[Math.floor(list.length * Math.random())]
const randomObject = (items) => {
const itemType = randomChoice(Object.keys(items))
const modifier = randomChoice(items[itemType])
return `${modifier} ${itemType}`
}
randomObject(items) //=> "marble table" or "plastic pen", etc.
评论要求选择某种类型的随机元素。这种变化将允许:
const randomOfType = (items, itemType) => {
const modifier = randomChoice(items[itemType])
return `${modifier} ${itemType}`
}
const randomObject = (items) => randomOfType(items, randomChoice(Object.keys(items)))
randomOfType(items, 'table') //=> "oak table" or "marble table", etc.