.map一个数组,以便它只保留每个元素的前5个字符?

时间:2014-03-30 03:40:13

标签: javascript

我尝试使用.map函数更改此数组,以便我只有前5个字符,例如" 01:00"," 02:00" ?

这是数组:

["01:00:00 AM", "02:00:00 AM", "03:00:00 AM", "04:00:00 AM", "05:00:00 AM", "06:00:00 AM", "07:00:00 AM", "08:00:00 AM", "09:00:00 AM", "10:00:00 AM", "11:00:00 AM", "12:00:00 PM", "13:00:00 PM", "14:00:00 PM", "15:00:00 PM", "16:00:00 PM", "17:00:00 PM", "18:00:00 PM", "19:00:00 PM", "20:00:00 PM", "21:00:00 PM", "22:00:00 PM", "23:00:00 PM", "00:00:00 AM"]

1 个答案:

答案 0 :(得分:2)

首先定义一个函数来获取字符串的前5个字符:

function first5(str){return str.substring(0, 5)}

然后将函数传递给array.map:

arr = ["01:00:00 AM", "02:00:00 AM", "03:00:00 AM"]  // you can use your full array here
arr.map(first5) //=> ["01:00", "02:00", "03:00"]

如果你看一下documentation的array.map,它(就像javascript中的许多其他函数一样)将一个函数作为输入。