我有一个单独的字符串值,如15,16,17,我想将其转换为[" 15"," 16"," 17"]使用angular js 1.x或java script.Please帮助我
我的Angular js代码是
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Array items
<code style="display: block; padding: 8px;">{{selected | json}}</code>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selected = [];
$scope.selected = ["15","16","17"];
$scope.existvalues=15,16,17;
//$scope.selected=$scope.existvalues;
/*Instead of above static code i want assign a comma separated string dynamic value like
this $scope.existvalues=15,16,17;
How i convert and assign $scope.existvalues to $scope.selected array like ["15","16","17"]
*/
});
</script>
</body>
</html>
&#13;
答案 0 :(得分:3)
使用split()
将字符串转换为数组
var str = "15,16,17"
var strArr = str.split(',');
console.log(strArr); // gives ["15","16","17"];
&#13;
或根据您的示例将其加入
$scope.existvalues="15,16,17";
$scope.selected = $scope.existvalues.split(',');
console.log($scope.selected); // gives ["15","16","17"]
答案 1 :(得分:1)
对字符串使用Split方法,它会根据您要求拆分的字符串拆分字符串(&#34;在,
拆分&#34;)并将答案作为数组返回
str = "15,16,17"
strAsArray = str.split(",")
console.log(strAsArray)
&#13;