为什么我不能在JavaScript设置数组元素(字符串)的属性? [英] Why can't I set properties of an array element (a string) in JavaScript?

查看:102
本文介绍了为什么我不能在JavaScript设置数组元素(字符串)的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var array = ['a', 'b', 'c'];
array[0].property = 'value';

alert(array[0].property);   
alert(array[0].property = 'value');
alert(array[0].property);   

结果如何呢? 未定义'值',那么未定义

为什么不是这个code按预期工作?

Why isn't this code working as expected?

推荐答案

该阵列是无关紧要的 - 你想设置一个属性上的原始

The Array is irrelevant - you're trying to set a property on a primitive:

一个数据是不是的目标并做
  没有任何方法。 JavaScript有5
  原始的数据类型 字符串 数量
  布尔 未定义。随着
  空的例外,不确定,所有的
  原语的值有对象
  其中等值包装各地
  基本值,例如一个字符串对象
  环绕字符串原始。所有
  原语的一成不变

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

如果你绝对必须使用属性字符串中随身携带这些额外的信息,另一种是使用对象等价的:

If you absolutely must use a property to carry this additional information around in a string, an alternative would be to use the object equivalent:

>>> var array = [new String('a'), new String('b'), new String('c')];
>>> array[0].property
undefined
>>> array[0].property = 'value'
"value"
>>> array[0].property
"value"

一个潜在的疑难杂症看出来的,如果你做到这一点,以后需要检测值是一个字符串:

A potential gotcha to look out for if you do this and later need to detect that the value is a string:

>>> var a = ['s', new String('s')];
>>> a.map(function(s) { return typeof s; });
["string", "object"]
>>> a.map(function(s) { return s instanceof String });
[false, true]
>>> a.map(function(s) { return Object.prototype.toString.call(s) == '[object String]' });
[true, true]

这篇关于为什么我不能在JavaScript设置数组元素(字符串)的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆