gpt4 book ai didi

Javascript - 使函数为每个 div 返回唯一的结果

转载 作者:行者123 更新时间:2023-12-03 00:27:44 26 4
gpt4 key购买 nike

我需要此函数在可变数量的 div 上运行,并为每个 div 返回唯一的结果。

class Sentence {
constructor(na, num, col) {
this.name = na;
this.number = num;
this.color = col;
}

makesentence() {
$('div').html(this.name + " is " + this.number + " years old and loves " + this.color);
}
}



var names = ['zach', 'kelly', 'lisa', 'slater'],
name = names[Math.floor(Math.random() * names.length)],
colors = ['red', 'orange', 'blue', 'magenta'],
color = colors[Math.floor(Math.random() * colors.length)],
number = Math.floor((Math.random() * 95) + 1);



var newsentence = new Sentence(name, number, color);
newsentence.makesentence();

所以,如果我的 HTML 是 3 个空 div:

<div></div>
<div></div>
<div></div>

我希望它返回类似的内容:
lisa 67岁,喜欢红色
zach 56 岁,喜欢洋红色
凯莉今年 27 岁,喜欢橙色

但现在它只返回类似的内容:
lisa 67岁,喜欢红色
lisa 67岁,喜欢红色
lisa 67 岁,喜欢红色

最佳答案

如果我正确理解你的问题,那么通过围绕 <div> 的迭代重新组织代码就可以很容易地实现这一点。文档中的元素。

作为保证每个 div 的唯一结果的策略,您可以像这样打乱输入数据:

 names = names.sort(function() { return Math.random() - 0.5; });
colors = colors.sort(function() { return Math.random() - 0.5; });
ages = ages.sort(function() { return Math.random() - 0.5; });

然后迭代每个 <div> ,通过每个元素的 index 按顺序填充每个元素的内容这样:

$('div').each(function(index) {

var name = names[index];
var color = colors[index];
var number = ages[index];

$(this).html(name + " is " + number + " years old and loves " + color);
});

这里的想法是首先对输入数据进行洗牌(即实现随机结果),然后在生成句子时有序访问该数据,这确保了最终结果中句子之间的唯一性。

这是一个工作片段,展示了这两个想法的实际应用:

// Declare input data to be used for sentense generation. 
// Also declare age data array
var names = ['zach', 'kelly', 'lisa', 'slater'];
var colors = ['red', 'orange', 'blue', 'magenta'];
var ages = new Array(100).fill(0).map((value, index) => index + 1);

// Shuffle the input data to yield a randomized result
names = names.sort(function() { return Math.random() - 0.5; });
colors = colors.sort(function() { return Math.random() - 0.5; });
ages = ages.sort(function() { return Math.random() - 0.5; });

// Iterate over each div in the document
$('div').each(function(index) {

// Get data from each array by current div's index
var name = names[index];
var color = colors[index];
var number = ages[index];

// For the current div, update the html content as before
$(this).html(name + " is " + number + " years old and loves " + color);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>

关于Javascript - 使函数为每个 div 返回唯一的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54014808/

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