【问题标题】:dynamic data when printed on the console is shown differently when compared with the static data when printed与打印时的静态数据相比,在控制台上打印的动态数据显示不同
【发布时间】:2019-01-28 23:23:44
【问题描述】:

如下所示,我将一个带有逗号分隔值的字符串从弹簧控制器返回到角度控制器。

app.controller('myListController', ['$scope', function ($scope) {

//get data dynamically , logic..
$scope.myList = response;
console.log("$scope.myList  " + $scope.myList); // "one,two","three","four","five,eight,nine"

//here i want to print as one,two,three,four,five,eight,nine 

//convert string to array with comma separated values
var array_list = JSON.parse($scope.myList);
   console.log("array_list :: " + array_list);
}]);

以上代码报错

angular.min.js?dummy=0.6014859345541128:119 SyntaxError: Unexpected token , in JSON at position 15
    at JSON.parse (<anonymous>)

相同的代码,当替换为静态代码时,它按预期工作。 示例:

   $scope.myList = ["one,two","three","four","five,eight,nine"];

   console.log("$scope.myList static content:: " +   $scope.myList); //one,two,three,four,five,eight,nine

以上有什么意见吗?

【问题讨论】:

    标签: javascript angularjs html-parsing


    【解决方案1】:

    JSON.parse 需要一个字符串作为输入,该字符串是有效的 JSON,并返回一个 JavaScript 对象。

    JSON.stringify 需要一个 JavaScript 对象作为输入并返回一个字符串。

    从您的示例看来,您正在将 $scope.myList (一个 JavaScript 数组)传递到 JSON.parse 中,期望得到一个字符串结果。如果 $scope.myList 是 JavaScript 对象,请使用 .stringify

    如果您要查找的结果是一、二、三、四、五、八、九,那么您应该使用 Array.join 方法。 EX// $scope.myList.join()

    【讨论】:

    • 当使用 JSON.stringify($scope.myList) 结果是 "\"one,two\",\"three\",\"four\",... 但我想要结果一,二,三,四,五,八,九@thstark
    • 在这种情况下,您应该使用 $scope.myList.join() ...无需使用 JSON 助手 ...
    【解决方案2】:

    正如我在您的 JSON.stringify 结果中看到的,您的响应字符串必须是这个值:

    '"one,two","three","four","five,eight,nine"'
    

    如果是,您可以使用简单的正则表达式来获得您想要的结果:

    var result = $scope.myList.replace(/"/g, ""); //"one,two,three,four,five,eight,nine"
    

    如果这不起作用,请分享您的 $scope.myList 的确切值

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2019-05-31
      • 2018-08-03
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多