简体   繁体   中英

Double square brackets with array.push() — JavaScript

In the code below all I'm trying to do at the moment is split the time variables (time11 and time12) into the hour and minutes value and push those values into an array (array1 for time11 hours & minutes and array 2 for time12 hours & minutes). The problem I'm having is when I print the arrays to the console they are displayed as [["17", "50"]] and [["04", "34"]] where I'd ideally like them to printed like ["17", "50"] & ["04", "34"]. Does anyone know why it's producing 2 sets of square brackets and how to get rid of the outer set. All help is appreciated.

Thanks

var time11 = "17:50";
var time12 = "04:34";

array1 = [];
array2 = [];

var timeDifference = function(time1, time2){
    array1.push(time1.split(/[^\d]/));
    array2.push(time2.split(/[^\d]/));
    console.log(array1);
    console.log(array2);
};

timeDifference(time11, time12);

push adds an element to an array, and split returns an array. You're therefore adding an array as an element to an array; both of your arrays have one element, which is an array.

The method you're looking for, is concat which will concatenate 2 arrays. But since you're starting from an empty array, you might as well just assign the output of split to the array:

array1 = time1.split(/[^\d]/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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