Splitting a string then accessing array
New to Javascript and jQuery, so I assume this is a pretty simple question.
I have a date I want to split into a string, then print out the array.
var date = "12开发者_如何学C/10/2010";
var dateArray = date.split(/);
$('#printbox').html($(dateArray[0]));
<span id="printbox"></span>
Edit: The question is, how can I split "12/10/2010" into an array like this:
Array[0] = 12
Array[1] = 10
Array[3] = 2010
And how do I print them to HTML?
The first parameter to the string.split function should be a string or regex:
var date = "12/10/2010";
var dateArray = date.split("/");
// dateArray[0] == 12
// dateArray[1] == 10
// dateArray[2] == 2010
// Now use the array to print out whichever way you want (jQuery.html(values))...
var date = "12/10/2010";
var dateArray = date.split('/');
$('#printbox').html(dateArray[0]); // it displays 12 in printbox
$('#printbox').html(dateArray[1]); // it displays 10 in printbox
$('#printbox').html(dateArray[2]); // it displays 2010 in printbox
For splitting you were almost there :)
var dateArray = date.split("/");
If you want to use jQuery you could use the each method.
$.each(dateArray, function(index, value) {
// print out here
});
This constructs a loop that iterates over the elements in your array. You can access this element by the value
variable.
var date = "12/10/2010";
var dateArray = date.split('/');
// dateArray => ['12', '10', '2010']
If you want to use jQuery there is an each function that you can use:
$.each(dateArray, function (index, value) {
$('#printbox').append(value);
});
There is also a .forEach method in newer browsers:
dateArray.forEach(function (value) {
document.getElementById('printbox').
appendChild(document.createTextNode(value));
});
Older browsers can have this method via the Array.prototype:
if (!(Array.prototype.forEach === 'function')) {
Array.prototype.forEach = function (fn) {
for (var i = 0, l = this.length; i < l; i += 1) {
fn(this[i]);
}
};
}
var date = "12/10/2010";
var dateArray = date.split(/\//); // have to quote regular expressions with /
document.write; // this does nothing
$('#printbox').html(dateArray[2] + '-' + dateArray[0] + '-' + dateArray[1]); // do what you want here. The code I provided should print 2010-12-10
var date = "12/10/2010";
var dateArray = date.split('/');
var year = dateArray.splice(2,1);
dateArray[3] = year;
should give you
Array[0] = 12
Array[1] = 10
Array[3] = 2010
But why you need the year in the fourth key I don't know. (also removes from the third so you don't end up with two years)
精彩评论