[英]Splitting a string then accessing array
New to Javascript and jQuery, so I assume this is a pretty simple question. Java和jQuery的新手,所以我认为这是一个非常简单的问题。
I have a date I want to split into a string, then print out the array. 我有一个想要拆分为字符串的日期,然后打印出数组。
var date = "12/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: 编辑:问题是,我如何将“ 12/10/2010”拆分成这样的数组:
Array[0] = 12
Array[1] = 10
Array[3] = 2010
And how do I print them to HTML? 以及如何将它们打印为HTML?
The first parameter to the string.split function should be a string or regex: string.split函数的第一个参数应该是字符串或正则表达式:
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. 如果要使用jQuery,则可以使用each方法。
$.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. 您可以通过
value
变量访问此元素。
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: 如果要使用jQuery,则可以使用每个函数:
$.each(dateArray, function (index, value) {
$('#printbox').append(value);
});
There is also a .forEach method in newer browsers: 较新的浏览器中还有一个.forEach方法:
dateArray.forEach(function (value) {
document.getElementById('printbox').
appendChild(document.createTextNode(value));
});
Older browsers can have this method via the Array.prototype: 较旧的浏览器可以通过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)
(也可以从第三年中删除,这样您就不用两年了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.