javascript 如何在angularjs中使用split
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30123155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use split in angularjs
提问by d9.Kriangkraing
im get date for ng-model like that
我得到这样的 ng-model 的日期
Thu May 21 2015 18:47:07 GMT+0700 (SE Asia Standard Time)
2015 年 5 月 21 日星期四 18:47:07 GMT+0700(东南亚标准时间)
but it show me in console "TypeError: date.split is not a function
" how to fix it?
但它在控制台中向我显示"TypeError: date.split is not a function
“如何修复它?
$scope.test = function(date) {
console.log(date);
$scope.d = (date.split(' ')[0]);
$scope.m = (date.split(' ')[1]);
$scope.y = (date.split(' ')[2]);
$scope.dd = (date.split(' ')[3]);
}
回答by dfsq
The problem is that date
is not a String, it's a Dateobject instance. So you can't use split on it. In order to use it you might want to convert it to String first. For example like his:
问题是它date
不是一个字符串,它是一个Date对象实例。所以你不能对它使用 split 。为了使用它,您可能需要先将其转换为字符串。比如像他的:
$scope.test = function(date) {
date = date.toString();
$scope.d = (date.split(' ')[0]);
$scope.m = (date.split(' ')[1]);
$scope.y = (date.split(' ')[2]);
$scope.dd = (date.split(' ')[3]);
};
When you console log it console.log(date);
it calls toString
automatically that's why it looked like a string for you.
当您控制台记录它时,console.log(date);
它会toString
自动调用,这就是为什么它对您来说看起来像一个字符串。
Another thing, you really should not use split to extract data. Use methods of the Dateobject, like getMonth
, .getFullYear
, etc.
另一件事,你真的不应该使用 split 来提取数据。在使用方法日期对象,如getMonth
,.getFullYear
等。
回答by hoeni
Probably the date variable you get passed is not a string, but a Javascript Date objectwhich has no split()
method. You could go on and convert it to a string that you could split:
您传递的日期变量可能不是字符串,而是没有方法的Javascript Date 对象split()
。您可以继续将其转换为可以拆分的字符串:
$scope.d = (date.toString().split(' ')[0]);
Which would work but not be very efficient, because the date would be composed to a string and then parsed again. Better would be using the properties of the date object itself:
哪个可行但效率不高,因为日期将组成一个字符串,然后再次解析。最好使用日期对象本身的属性:
$scope.d = date.getDate();
$scope.m = date.getMonth() + 1;
$scope.y = date.getFullYear();
and so on...
等等...
Find all the useable methods on the reference. Even better would be keeping the date itself as it is and just using the date properties where you need them in the view, for example:
在参考资料中找到所有可用的方法。更好的是保持日期本身不变,并且只在视图中需要它们的地方使用日期属性,例如:
<div class="myDate">Year: {{date.getFullYear()}}