我正在尝试使用.pop()函数来获取我的数组的最后一个元素(这是我在网页上显示的计数)。我对Javascript / Jquery很新,所以我对此有点挣扎......
var notif_count = data.pop();
我收到错误“Uncaught TypeError:data.pop不是函数”
我在控制台中的数据看起来像一个多维数组,但我不确定?以下是输出示例:
EDIT 2 - 输出是一个包含此处显示的字符的字符串。
[
[
{
"_can_chaccess": true,
"_can_chown": true,
"_can_delete": true,
"_can_modify": true,
"_can_read": true,
"created_at": "Wed Jan 04 17:33:13 UTC 2017",
"created_by": 25206,
"created_by_user[login_name]": "jamie.lowe@workbooks.com",
"created_by_user[person_name]": "Jamie Lowe",
"created_through": "Workbooks",
"created_through_reference": "",
"id": 117662,
"imported": false,
"key": "notifications",
"key10": "",
"key11": "",
"key12": "",
"key13": "",
"key14": "",
"key15": "",
"key16": "",
"key17": "",
"key18": "",
"key19": "",
"key2": "292801",
"key3": "47930",
"key4": "CASE-32109",
"key5": "",
"key6": "",
"key7": "",
"key8": "",
"key9": "",
"lock_version": 0,
"owner[login_name]": "jamie.lowe@workbooks.com",
"owner[person_name]": "Jamie Lowe",
"owner_id": 25206,
"type": "Private::Automation::ApiData",
"updated_at": "Wed Jan 04 17:33:13 UTC 2017",
"updated_by": 25206,
"updated_by_user[login_name]": "xxxx@workbooks.com",
"updated_by_user[person_name]": "Jamie Lowe",
"value": ""
},
{
"_can_chaccess": true,
"_can_chown": true,
"_can_delete": true,
"_can_modify": true,
"_can_read": true,
"created_at": "Wed Jan 04 17:23:21 UTC 2017",
"created_by": 25206,
"created_by_user[login_name]": "jamie.lowe@workbooks.com",
"created_by_user[person_name]": "Jamie Lowe",
"created_through": "Workbooks",
"created_through_reference": "",
"id": 117660,
"imported": false,
"key": "notifications",
"key10": "",
"key11": "",
"key12": "",
"key13": "",
"key14": "",
"key15": "",
"key16": "",
"key17": "",
"key18": "",
"key19": "",
"key2": "292801",
"key3": "47930",
"key4": "CASE-32106",
"key5": "",
"key6": "",
"key7": "",
"key8": "",
"key9": "",
"lock_version": 2,
"owner[login_name]": "jamie.lowe@workbooks.com",
"owner[person_name]": "Jamie Lowe",
"owner_id": 25206,
"type": "Private::Automation::ApiData",
"updated_at": "Wed Jan 04 17:30:39 UTC 2017",
"updated_by": 25206,
"updated_by_user[login_name]": "xxxx@workbooks.com",
"updated_by_user[person_name]": "Jamie Lowe",
"value": ""
}
],
2
]
基本上我正试图在结束前的数组末尾获得数字2 - 我该怎么做?
编辑:完整代码示例
var notif_count = data[1]; <!-- Last element in the array which is the count of notifications calculated server side by PHP -->
console.log(notif_count);
$('#count').text(notif_count);
答案 0 :(得分:0)
使用数组索引。有关JS中的数组的更多详细信息,请查看MDN。
对于你的问题,这可行 -
var notif_count = data[1]
//index 1 will give 2nd element, as array indexing is zero indexing.
var notif_count = data.pop();
对我有用。检查FF控制台。相同的例子没有区别。
注意JSON字符串中的新行字符。
答案 1 :(得分:0)
根据您在评论中提供的反馈进行编辑。首先需要使用JSON.parse将字符串转换为列表,然后选择索引中的最后一项:
var data = '["a","b","c"]';
data_2 = JSON.parse(data)
var notif_count = data_2[data_2.length-1];
console.log(notif_count) --> 'c'
console.log(data_2) --> ['a','b','c']