javascript - Select random entry from string list in javascript
问题描述
Ok, so I have the following code which successfully generates a list (from an element);
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);
});
});
})`
which results in a (long) list of bike makes, as below;
My question is, how do I randomly select an entry from this list?
I've tried to split the results;
var elementMakesArray = makeValue.split('');
console.log(elementMakesArray);`
but this gave me the following;
I tried this;
var randomMake = Math.floor(Math.random() * makeValue);
console.log(randomMake);`
but got a NaN error.
So I'm just wondering how I can randomly select an entry from the list?
Any help would be greatly appreciated.
Thanks.
解决方案
您的代码为其找到的每个元素写入一个字符串值。您需要做的是获取这些字符串值并将它们添加到数组中,然后您可以从数组中获取随机条目:
let results = []; // <-- This is the array that the results will go into
this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (result) {
result.value.forEach(element => {
this.elementIdValue(element.ELEMENT, function (text) {
results.push(text.value); // Place individual result into array
});
});
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
推荐阅读
- c++ - 在 C++20 中具有向后兼容概念的推荐方法
- jquery - DOM 元素上的 jQuery 事件无法正常工作
- angular - Tippy/NgNeat/Helipopper 如何在 Angular 11 中单击时关闭
- javascript - 文本区域返回空值
- c++ - GCC codegen:pthread_create_key() 与 std::shared_ptr 复制有什么关系?
- python - 如何在 python 中设置与本地 hmail 服务器的连接?
- docker - WordPress docker设置的权限问题
- vuejs2 - vue3 嵌套搜索过滤器
- python - 刷新/重新加载 Python 脚本的一部分而不重新加载整个脚本
- oracle-apex - 如何禁用从顶点 oracle 的页面自动更新区域的代码?