Javascript 索引为字符串的数组中的随机字符串
我想从数组中随机选取一个项目。问题是数组的索引是字符串。如何从该数组中选择具有随机索引的项 注意:索引是字符串,我找到的答案是整数索引,但不是字符串Javascript 索引为字符串的数组中的随机字符串,javascript,react-native,Javascript,React Native,我想从数组中随机选取一个项目。问题是数组的索引是字符串。如何从该数组中选择具有随机索引的项 注意:索引是字符串,我找到的答案是整数索引,但不是字符串 //................................................ const styles = StyleSheet.create({ bigBlue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: {
//................................................
const styles = StyleSheet.create({
bigBlue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 30,
},
red: {
color: 'red',
},
});
//.......................................................
return (
//if index was integer
<Text style={styles[Math.floor(Math.random()*styles.length)]}>{this.props.text}</Text>
// I need something like this : styles[RandomStringIndex()]
);
听起来您需要Object.keys或Object.values 这两种方法都将对象的键:值映射转换为带编号的数组 Object.keys方法: Object.values方法:
请包含代码,显示您当前拥有的内容。这将是一个问题
var array_of_keys = Object.keys(styles);
var random_key = array_of_keys[Math.floor(Math.random()*array_of_keys.length)];
var random_value = styles[random_key];
var array_of_values = Object.values(styles);
var random_value = array_of_values[Math.floor(Math.random()*array_of_values.length)];