我有以下代碼需要獲取隨機值:
const namesJson = {
"nombre1": "Raghat",
"nombre2": "Uhmla",
"nombre3": "Borto"
};
const btnName = document.getElementById('btn')
btnName.onclick = function names() {
var properties = Object.getOwnPropertyNames(namesJson);
var index = Math.floor(Math.random() * properties.length);
var output = {};
output[properties[index]] = namesJson[properties[index]];
document.getElementById("mensaje").innerHTML = JSON.stringify(output);
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje:</h2>
<div id="mensaje"></div>
有了這個我有{"nombre2": "Uhmla"}
我想得到這樣的價值Uhmla,我該怎么辦?
uj5u.com熱心網友回復:
您可以使用Object.values以獲取值陣列,然后使用亂數您可以在不進行字串化的情況下獲取值,因此無需":
const namesJson = {
"nombre1": "Raghat",
"nombre2": "Uhmla",
"nombre3": "Borto"
};
const btnName = document.getElementById('btn')
btnName.onclick = function names() {
var properties = Object.values(namesJson);
var index = Math.floor(Math.random() * properties.length);
document.getElementById("mensaje").innerHTML = properties[index];
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje:</h2>
<div id="mensaje"></div>
uj5u.com熱心網友回復:
嘗試這個:
const namesJson = {
"nombre1": "Raghat",
"nombre2": "Uhmla",
"nombre3": "Borto"
};
const names = Object.values(namesJson); // or just ["Raghat", "Uhmla", "Borto"];
const btnName = document.getElementById('btn')
btnName.onclick = () => {
document.getElementById("mensaje").innerHTML =
names[Math.floor(Math.random() * names.length)]
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje</h2>
<div id="mensaje"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/426980.html
標籤:javascript json 细绳
下一篇:如何從開頭提取子字串到一個字符?
