[英]Array.length in Javascript is not working
I tried to get length from array but it worked abnormally.我试图从数组中获取长度,但它工作异常。 Here is my object,
这是我的对象,
var user = {
"username":"testuser update",
"email":"user001@mail.co.th",
"name":"user001",
"ownAccount":"[
{"id":2,"name":"Demo Account2"},
{"id":1,"name":"Demo Account"}
]"
}
I want to get length of ownAccount, I tested by logging it,我想获得 ownAccount 的长度,我通过记录它进行了测试,
console.log(user.ownAccount.length);
It showed 64 !!!, it didn't show 2 .它显示64 !!!,它没有显示2 。 I didn't understand what I did wrong.
我不明白我做错了什么。
Thanks for help.感谢帮助。
Its not an array you need to parse it first to get as an array :它不是一个数组,你需要先解析它才能得到一个数组:
var ownAc=JSON.parse(user.ownAccount)
console.log(ownAc.length);
Use the simple method Object.keys(obj)
with the reference of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys使用简单的方法
Object.keys(obj)
参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
In your case the answer is Object.keys(user.ownAccount).length
在你的情况下,答案是
Object.keys(user.ownAccount).length
var user = { "username": "testuser update", "email": "user001@mail.co.th", "name": "user001", "ownAccount": [{ "id": 2, "name": "Demo Account2" }, { "id": 1, "name": "Demo Account" } ] }; console.log(Object.keys(user.ownAccount).length);
The array
is defined as a string
, you should remove the double quotes. array
定义为string
,您应该删除双引号。 In other terms, replace "[
with [
and ]"
with ]
.换句话说,将
"[
与[
和]"
替换为]
。
"[ {"id":2,"name":"Demo Account2"}, {"id":1,"name":"Demo Account"} ]" "[ {"id":2,"name":"Demo Account2"}, {"id":1,"name":"Demo Account"} ]"
try this code试试这个代码
[
{"id":2,"name":"Demo Account2"},
{"id":1,"name":"Demo Account"}
]
try this code with your json data用你的 json 数据试试这个代码
var user = {
"username":"testuser update",
"email":"user001@mail.co.th",
"name":"user001",
"ownAccount":"[
{"id":2,"name":"Demo Account2"},
{"id":1,"name":"Demo Account"}
]"
}
user.ownAccount = JSON.parse(user.ownAccount)
console.log(user.ownAccount.length);
Try this:尝试这个:
var user = {
username:"testuser update",
email:"user001@mail.co.th",
name:"user001",
ownAccount:[
{id:2,name:"Demo Account2"},
{id:1,name:"Demo Account"}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.