如何从字符串中的数组中获取随机对象

时间:2022-10-07 03:37:29

Im trying to get a random object from an array, and add it to a string.

我试图从数组中获取一个随机对象,并将其添加到字符串中。

var input = ['1', '2', '3']
    console.log(input[Math.floor(Math.random() * input.length)] + " some text")

However, when you run this, it does nothing. If you label this post as a duplicate, please know that the question is not asking how to randomize an array, my question is how do I add an object from an array, and add it to a string.

但是,当你运行它时,它什么都不做。如果你把这篇文章标记为重复,请知道问题不是询问如何随机化一个数组,我的问题是如何从数组添加一个对象,并将其添加到一个字符串。

1 个解决方案

#1


0  

Your are trying to add a string from array instead of object. And your code works fine, try this.

您正在尝试从数组而不是对象添加字符串。你的代码工作正常,试试这个。

"use strict";

let input = ['1', '2', '3'];
let amount = input.length;

console.log(input[Math.floor(Math.random() * amount)] + " some text");

#1


0  

Your are trying to add a string from array instead of object. And your code works fine, try this.

您正在尝试从数组而不是对象添加字符串。你的代码工作正常,试试这个。

"use strict";

let input = ['1', '2', '3'];
let amount = input.length;

console.log(input[Math.floor(Math.random() * amount)] + " some text");