首页 > 解决方案 > 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;

enter image description here etc, etc

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;

enter image description here

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.

标签: javascriptstringrandom

解决方案


您的代码为其找到的每个元素写入一个字符串值。您需要做的是获取这些字符串值并将它们添加到数组中,然后您可以从数组中获取随机条目:

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

推荐阅读