Javascript-尝试使用Array.lenght访问foreach循环中每个数组的最后一个元素
我需要显示来自数组的用户文本消息的预览。如果我硬编码循环中的数字,我很容易实现这一点。它能工作,但不漂亮。一个更漂亮的解决方案是显示收到或发送的最后一条短信。我试图用Javascript-尝试使用Array.lenght访问foreach循环中每个数组的最后一个元素,javascript,arrays,foreach,Javascript,Arrays,Foreach,我需要显示来自数组的用户文本消息的预览。如果我硬编码循环中的数字,我很容易实现这一点。它能工作,但不漂亮。一个更漂亮的解决方案是显示收到或发送的最后一条短信。我试图用Array.Length来实现这一点的尝试失败得很惨,因为并非所有用户都有相同数量的文本消息。如果一个用户有4条消息和另外2条消息,那么当在消息较少的用户上循环时,将导致未定义的错误。如何做到这一点 txt.details[0].message //works but not pretty 作用 function getSMS()
Array.Length
来实现这一点的尝试失败得很惨,因为并非所有用户都有相同数量的文本消息。如果一个用户有4条消息和另外2条消息,那么当在消息较少的用户上循环时,将导致未定义的错误。如何做到这一点
txt.details[0].message //works but not pretty
作用
function getSMS(){
usersms.forEach(function (txt,counter) {
//
//
//get total number of msgs per user
var usertxtarray = txt.details;
var length = (usertxtarray).length;
console.log('msgs per user : ' + length);//prints 2, 2, 4
//display sms preview
var sms = (txt.details[length].message).substring(0,35) + '...';
//etc...
});
}
下面是(txt.details)
的样子
[
{
"direction": "from",
"user": {
"id": "23",
"avatar": "myavatar.jpg",
"first_name": "Jane",
"last_name": "Doe",
},
"message": "Lorem ipsum dolor sit amet, Arrays are zero-indexed.
So if your length = 4, then your last item is at index 3.
So ...
var sms = txt.details[length - 1].message.substring(0, 35) + '...';
[
{
“方向”:“从”,
“用户”:{
“id”:“23”,
“阿凡达”:“myavatar.jpg”,
“名字”:“简”,
“姓氏”:“Doe”,
},
“消息”:“Lorem ipsum dolor sit amet,数组为零索引
因此,如果长度=4,那么最后一项位于索引3
所以
将给您最后一条消息。数组的索引为零
因此,如果长度=4,那么最后一项位于索引3
所以
我会给你最后的信息