【问题标题】:JSON returned from PHP is interpreted as Array instead of Object by Javascript [duplicate]从PHP返回的JSON被Javascript解释为数组而不是对象[重复]
【发布时间】:2018-01-04 01:10:17
【问题描述】:

PHP:

echo json_encode(array("apple", "banana"), JSON_FORCE_OBJECT);

AJAX(带有 jQ​​uery 的客户端 javascript):

$.ajax({
  ...
  ...
  success: function (data) {
    console.log(data);       
    data1 = JSON.parse(data);
    console.log(data1["0"]);
  },
});

控制台:

{"0":"apple", "1":"banana"}
apple

我的问题:

如果我将console.log(data1["0"]) 替换为console.log(data1.0),它不会选择apple,并且我收到错误missing ) after argument list。为什么只有 array notation 有效,为什么 object notation 无效?

(我怀疑它与“纯数组”有关——即不是“关联数组”——被编码为的原始数组的性质PHP 中的 JSON。这种类型的对象字面量是否有 Javascript 解释为纯数组而不是对象的名称?)

【问题讨论】:

    标签: php arrays json javascript-objects


    【解决方案1】:

    以数字开头的 JavaScript 属性不能用点表示法引用;并且必须使用括号表示法访问。

    以下解释直接摘自: https://developer.mozilla.org/en/US/docs/Web/JavaScript/Reference/Global_Objects/Array

    访问数组元素

    JavaScript 数组是零索引的:数组的第一个元素位于索引 0 处,最后一个元素位于等于数组长度属性值减 1 的索引处。使用无效的索引号返回未定义。

    var arr = ['this is the first element', 'this is the second element', 'this is the last element'];
    console.log(arr[0]);              // logs 'this is the first element'
    console.log(arr[1]);              // logs 'this is the second element'
    console.log(arr[arr.length - 1]); // logs 'this is the last element'
    

    数组元素是对象属性,就像 toString 是属性一样,但是尝试如下访问数组元素会引发语法错误,因为属性名称无效:

    console.log(arr.0); // a syntax error
    

    JavaScript 数组和导致这种情况的属性没有什么特别之处。以数字开头的 JavaScript 属性不能用点表示法引用;并且必须使用括号表示法访问。例如,如果您有一个具有名为“3d”的属性的对象,则只能使用括号表示法来引用它。例如:

    var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
    console.log(years.0);   // a syntax error
    console.log(years[0]);  // works properly
    renderer.3d.setTexture(model, 'character.png');     // a syntax error
    renderer['3d'].setTexture(model, 'character.png');  // works properly
    

    请注意,在 3d 示例中,必须引用“3d”。也可以引用 JavaScript 数组索引(例如,years['2'] 而不是 years[2]),尽管这不是必需的。 Years[2] 中的 2 被 JavaScript 引擎通过隐式 toString 转换强制转换为字符串。正是由于这个原因,'2' 和 '02' 将引用 years 对象上的两个不同插槽,以下示例可能是正确的:

    console.log(years['2'] != years['02']);
    

    同样,恰好是保留字(!)的对象属性只能作为括号符号中的字符串文字访问(但至少可以在 firefox 40.0a2 中通过点符号访问):

    var promise = {
      'var'  : 'text',
      'array': [1, 2, 3, 4]
    };
    
    console.log(promise['var']);
    

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 2013-09-23
      • 2016-08-13
      • 2021-05-20
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多