如何使用 JQuery 找出 JSON 文件对象内嵌套数组的数量?
How to find out the amount of nested arrays inside the object of a JSON file with JQuery?
我正在尝试找出正确的方法来获取 JSON 文件中对象中嵌套数组的数量。自从我用 JQuery 编写了 AJAX 代码后,这让我有点搞砸了。我需要这个,所以我可以将它用作要在随机数生成器中相乘的数字。
我已经尝试在 Math.round(Math.random() * x + 1);
中使用 response.length
属性 但它只是 return 编辑了数字 1.
JSON (people.json) :
[
{
"name" : "Jason",
"id" : "1"
},
{
"name" : "Alek",
"id" : "2"
},
{
"name" : "Julian",
"id" : "3"
}
]
JS:
$(document).ready(function () {
let url = 'data/people.json';
$.getJSON(url, function (response){
//let randomNum = Math.round(Math.random() * ~LENGTH~);
});//END getJSON
}); //END OF READY FUNCTION
我希望变量 randomNum 为 return 1-3 之间的数字(JSON 文件中我的对象内的嵌套数组的数量。)
提前致谢。
我已经使用 this link 得到 json 但它是您指定的格式。
$(document).ready(function () {
let url = 'https://jsonplaceholder.typicode.com/users';
$.getJSON(url, function (response){
var length = response.length;
let randomNum = Math.round(Math.random() * length);
alert('random number is ' + randomNum);
});//END getJSON
}); //EN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我正在尝试找出正确的方法来获取 JSON 文件中对象中嵌套数组的数量。自从我用 JQuery 编写了 AJAX 代码后,这让我有点搞砸了。我需要这个,所以我可以将它用作要在随机数生成器中相乘的数字。
我已经尝试在 Math.round(Math.random() * x + 1);
中使用 response.length
属性 但它只是 return 编辑了数字 1.
JSON (people.json) :
[
{
"name" : "Jason",
"id" : "1"
},
{
"name" : "Alek",
"id" : "2"
},
{
"name" : "Julian",
"id" : "3"
}
]
JS:
$(document).ready(function () {
let url = 'data/people.json';
$.getJSON(url, function (response){
//let randomNum = Math.round(Math.random() * ~LENGTH~);
});//END getJSON
}); //END OF READY FUNCTION
我希望变量 randomNum 为 return 1-3 之间的数字(JSON 文件中我的对象内的嵌套数组的数量。)
提前致谢。
我已经使用 this link 得到 json 但它是您指定的格式。
$(document).ready(function () {
let url = 'https://jsonplaceholder.typicode.com/users';
$.getJSON(url, function (response){
var length = response.length;
let randomNum = Math.round(Math.random() * length);
alert('random number is ' + randomNum);
});//END getJSON
}); //EN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>