angularjs将字符串推送到数组

时间:2014-09-03 10:30:10

标签: arrays angularjs

我遇到了如何格式化数组的问题,这是我的例子:

var code = 743919183;
var tempPost = '["'+code+'"]';
$scope.arrayTwo = [];
$scope.arrayTwo.push(code);

在控制台中:

tempPost将输出如下: ["743919183"]

while $scope.arrayTwo,在双引号之前和之后都有空格       [ "743919183" ]

我希望$scope.ArrayTwo数组格式化为tempPost,我该怎么做?

3 个答案:

答案 0 :(得分:2)

我不确定你想要达到的目的但是:

var code = 743919183; //This is an integer to convert to string just call .toString()
var tempPost = '["'+code+'"]'; //This is a string that has a value equal to "["743919183"]", this is not an array.
$scope.arrayTwo = [] //This is a an empty array;
$scope.arrayTwo.push(code); //This will add a new item to the array in this case the integer code. Your array would look like [743919183].

现在,如果您想要的是一个数组,其中包含一个代码作为字符串的项目,您应该这样做:

var code = "743919183";
$scope.arrayTwo = [code];

或者:

var code = 743919183;
$scope.arrayTwo = [code.toString()];

答案 1 :(得分:0)

如果你只是希望它看起来像数组格式而不是实际的数组,你可以这样做:

var code = 743919183;
var tempPost = '["'+code+'"]';
$scope.arrayTwo = [];
$scope.arrayTwo.push(code);

这就是你想要的吗?

或者你可以这样做

var code = 743919183;
$scope.arrayTwo = [];

function Str2Arr() {

  s = '';

  for (var i=0; i<code.length; i++) {

    if (code[i] != ',') { s += code[i]; }

                  else { arrayTwo .push(s);  s = ''; }

  } 

  arrayTwo .push(s);

  alert(arrayTwo .join('\n'));

}

Str2Arr();

答案 2 :(得分:0)

var code = 743919183;
var tempPost = '["'+code+'"]';
$scope.arrayTwo = [];
$scope.arrayTwo.push(code);

在firefox $scope.arrayTwo中返回[“743919183”]和chrome [“743919183”](chrome中没有空格)。所以我认为这不应该是代码中的问题。