最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using split pop and join all at once can it work? - Stack Overflow

programmeradmin5浏览0评论

I really love Javascript and I wrote my code like this. I feel like it should work. Am I doing it in the wrong order? If it won't work like this why not?

var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").pop().join(':'));

split() makes it an array, pop() takes off the end of the array, join() makes it a string again right?

I really love Javascript and I wrote my code like this. I feel like it should work. Am I doing it in the wrong order? If it won't work like this why not?

var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").pop().join(':'));

split() makes it an array, pop() takes off the end of the array, join() makes it a string again right?

Share Improve this question edited Jun 21, 2017 at 16:39 BenM 53.2k26 gold badges115 silver badges172 bronze badges asked Jun 21, 2017 at 16:39 Peter S McIntyrePeter S McIntyre 4134 silver badges12 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 10

You could use Array#slice with a negative end/second argument.

Array#pop returns the last element, but not the array itself. slice returns a copy of the array with all emements from start without the last element.

var mydate = new Date();
console.log(mydate.toLocaleTimeString().split(":").slice(0, -1).join(':'));

No, pop() will remove the last element from the array and return it.

To achieve what you're trying, you'll need to first assign the result of split() to a variable you can then reference:

var mydate = new Date(),
    myarr  = mydate.toLocaleTimeString().split(':');
    myarr.pop();

console.log(myarr.join(':'));

if all you want to achieve is hours:minutes, you can just simply do this

var mydate = new Date();
console.log(mydate.getHours() + ':' + mydate.getMinutes());

You are trying to use method chaining where next method in the chain uses the output of the previously executed method. Reason it's not working is because "join()" method is a prototype of an array but "pop()" returns an array element which doesn't aforementioned method that's why the error. refactor your code as below:

  var myDate = new Date(),
      myDateArr = myDate.toLocaleTimeString().split(':');
  myDateArr.pop(); // Remove the seconds
  myDate = myDateArr.join(':'); // Returns string
  console.log(myDate);

Hope this helps.

Try this

var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").slice(0, 2).join(":"));

发布评论

评论列表(0)

  1. 暂无评论