zoukankan      html  css  js  c++  java
  • 将数组格式的字符串转换成数组

      由于数据传输的原因,有时我们得到的是字符串形式的数组(比如:str='["a","b","c","d"]',写成str="['a', 'b', 'c', 'd']",使用JSON.parse()的时候会报错)。要将这种字符串还原成数组对象,有如下两种方法。

    1,使用 eval() 函数转换

    (1)eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。我们可以借助它来将字符串还原成数组。
    const str = '["a", "b", "c", "d"]';
    const arr =  eval('(' + str + ')');
    
    
    console.log(str)    // '["a", "b", "c", "d"]'
    console.log(arr)    // ["a", "b", "c", "d"]

    2,使用 JSON.parse() 方法转换

    (1)由于数组的类型也是对象,因此我们也可以用 JSON.parse() 方法将数组转换成对象。

    const str = '["a", "b", "c", "d"]';
    const arr =  JSON.parse(str);
    
    
    console.log(str)    // '["a", "b", "c", "d"]'
    console.log(arr)    // ["a", "b", "c", "d"]

    当str="['a', 'b', 'c', 'd']"时,JSON.parse()报错


     
  • 相关阅读:
    hust 1260 Dominos && hust 1516 Dominos
    poj 1149 PIGS
    hust 1230 beautiful
    poj 1469 COURSES
    hdu 3062 Party
    hust 1027 Enemy Target!
    hdu 3415 Max Sum of Max-K-sub-sequence
    简单的实现轮播代码
    window.parent与window.openner区别介绍
    plupload使用指南(转)
  • 原文地址:https://www.cnblogs.com/shy0113/p/12064590.html
Copyright © 2011-2022 走看看