从PHP返回的JSON被Javascript

时间:2018-01-04 01:10:17

标签: php arrays json javascript-objects

PHP:

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

AJAX(使用jQuery的客户端javascript):

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

CONSOLE:

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

我的问题:

如果我将console.log(data1["0"])替换为console.log(data1.0),则它不会选择apple而我会收到错误missing ) after argument list。为什么只有数组符号工作,为什么对象符号也不起作用?

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

1 个答案:

答案 0 :(得分:2)

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

  

以下说明直接取自:   https://developer.mozilla.org/en/US/docs/Web/JavaScript/Reference/Global_Objects/Array

访问数组元素

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

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'的属性,则只能使用括号表示法引用它。 E.g:

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数组索引(例如,年[' 2']而不是年[2]),尽管它不是必需的。 2年内[2]由JavaScript引擎通过隐式toString转换强制转换为字符串。出于这个原因,它是' 2' 2和' 02'将引用year对象上的两个不同的插槽,以下示例可能为真:

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

类似地,碰巧保留字(!)的对象属性只能以括号表示法的形式访问(但至少可以通过firefox 40.0a2中的点表示法访问):

var promise = {
  'var'  : 'text',
  'array': [1, 2, 3, 4]
};

console.log(promise['var']);