简体   繁体   English

Javascript - 尝试使用 Array.lenght 访问 foreach 循环中每个数组的最后一个元素

[英]Javascript - Trying to use Array.lenght to access last element of each array in a foreach loop

I need to display preview of user text messages from an array.我需要显示来自数组的用户文本消息的预览。 I achieve this easily if I hardcode the number in the loop.如果我硬编码循环中的数字,我很容易实现这一点。 It works but it's not pretty.它有效,但并不漂亮。 A prettier solution would be to display last text message received or sent.一个更漂亮的解决方案是显示最后接收或发送的文本消息。 My attempt at doing this with Array.Length is failing miserably because not all users have the same number of text messages.我使用Array.Length执行此操作的尝试失败得很惨,因为并非所有用户都拥有相同数量的短信。 If a user has 4 messages and another 2 messages, then it will cause an undefined error when looping over the users with less messages.如果一个用户有 4 条消息和另外 2 条消息,那么在遍历消息较少的用户时会导致未定义的错误。 How can this be done?如何才能做到这一点?

txt.details[0].message //works but not pretty

function function

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... 

});
}

Here's what (txt.details) looks like这是(txt.details)的样子

[
  {
    "direction": "from",
    "user": {
      "id": "23",
      "avatar": "myavatar.jpg",
      "first_name": "Jane",
      "last_name": "Doe",
    },
    "message": "Lorem ipsum dolor sit amet, 😆😆 consectetur adipiscing elit",
    "smsid": "2220",
    "date": "202-12-29",
    "time": "12:00",
    "timezone": "Eastern Standard Time"
  },
  {
    "direction": "to",
    "user": {
      "id": "23",
      "avatar": "myavatar.jpg",
      "first_name": "Jane",
      "last_name": "Doe",
    },
    "message": "Lorem ipsum dolor 😍 😎sit amet, consectetur adipiscing elit",
    "smsid": "2220",
    "date": "2021-01-05",
    "time": "09:00",
    "timezone": "Eastern Standard Time"
  }
]

Arrays are zero-indexed. Arrays 是零索引的。

So if your length = 4, then your last item is at index 3.因此,如果您的长度 = 4,那么您的最后一项在索引 3 处。

So...所以...

var sms = txt.details[length - 1].message.substring(0, 35) + '...';

will give you the last message.会给你最后一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM