猿问

从javascript中的字符串列表中选择随机条目

好的,所以我有以下代码成功生成列表(从元素);


this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (result) {

    result.value.forEach(element => {

        this.elementIdValue(element.ELEMENT, function (text) {

            var makeValue = text.value;

            console.log(makeValue);

        });

    });

})`

这会产生一个(长)自行车制造商列表,如下所示;

等等等等


我的问题是,如何从该列表中随机选择一个条目?


我试图分割结果;


var elementMakesArray = makeValue.split('');

console.log(elementMakesArray);`

但这给了我以下内容;

http://img1.mukewang.com/618e323e0001678105580260.jpg

我试过这个;


var randomMake = Math.floor(Math.random() * makeValue);

console.log(randomMake);`

但得到了一个 NaN 错误。


所以我只是想知道如何从列表中随机选择一个条目?


任何帮助将不胜感激。


HUWWW
浏览 294回答 2
2回答

素胚勾勒不出你

您的代码为它找到的每个元素写入一个字符串值。您需要做的是获取这些字符串值并将它们添加到数组中,然后您可以从数组中获取随机条目:let results = []; // <-- This is the array that the results will go intothis.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (result) {&nbsp; &nbsp; result.value.forEach(element => {&nbsp; &nbsp; &nbsp; &nbsp; this.elementIdValue(element.ELEMENT, function (text) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; results.push(text.value); // Place individual result into array&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });&nbsp; &nbsp; console.log(results); // Log the finished array after loop is done});// Now that the array is populated with strings, you can get one random one out:var rand = results[Math.floor(Math.random() * results.length)];console.log(rand); // Log the random string

HUH函数

let result = this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-menter code hereake > option', function (result) {&nbsp; &nbsp;return result.value.forEach(element => {&nbsp; &nbsp; &nbsp; return this.elementIdValue(element.ELEMENT, function (text) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return text.value;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })})var random = results[Math.floor(Math.random(`enter code here`) * results.length)];console.log(random); // Log the random string
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答